swift - What are the benefits of type constraints in protocol extensions? -


i'm programming beginner, please excuse naive question. swift first language , have no reference (other programming languages) compare benefits of type constrains on protocol extension.

personally, feel confused , weird. why type constraint on protocol extension exist? what's meaning of it?

protocol teamrecord {   var wins: int { }   var losses: int { }   func winningpercentage() -> double }  //constraint: extension customstringconvertible self: teamrecord {   var description: string {     return "\(wins) - \(losses)"   } }  struct baseballrecord: teamrecord {   var wins: int   var losses: int    func winningpercentage() -> double {     return double(wins) / double(wins) + double(losses)   } }   extension baseballrecord: customstringconvertible { }   print(baseballrecord(wins: 4, losses: 2)) 

question feel weird use where self constraint here, what's benefits of it? can achieve same result without using constraint staff?

thanks time , help

funny enough, "constraint" adds lots of power extensions.

without constraint conforming type of customstringconvertible teamrecord, compiler have no way of guaranteeing wins , losses properties exist.

type constraints (in general, not on protocol extensions) limit selection of types can possibly conform protocol, in exchange, buy compiler enforcement whatever properties/methods invoke available in conforming type.

consider example, keys of dictionary must hashable. dictionary relies on being able hash values of keys determine how store them. constraint important. without it, try using custom struct/object dictionary key. custom struct/object can't hashed, program do?

adding constraint gives compiler additional information guide me. it'll require me add conformance hashable, , won't compile without it.