1

Swift documentation says that protocols are treated like any other types, but looking at some examples, I see that 'type constraint' construct is being used instead of protocol.

Let's take the Swift dictionary for an example:

struct Dictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible {
  // ...
  subscript (key: Key) -> Value?    
  // ...
}

Couldn't that have been written like this

struct Dictionary<Value>: CollectionType, DictionaryLiteralConvertible {
  // ...
  subscript (key: Hashable) -> Value?    
  // ...
}

?

I can see type constraint useful with where conditions for types with associated types, but I'm not sure about this specific example.

Srđan Rašić
  • 1,597
  • 15
  • 23

1 Answers1

4

If you try to implement something like your second example, the compiler complains that Protocol 'Hashable' can only be used as a generic constraint because it has Self or associated type requirements. This is because Hashable ultimately extends Equatable, which requires that both the left-hand and right-hand side of a equality statement be the exact same type as each other. In your second example, though, you're simply requiring that the dictionary key be Hashable, not that all keys be the same concrete type. Take a look at this answer for a fuller explanation.

Community
  • 1
  • 1
NRitH
  • 13,441
  • 4
  • 41
  • 44
  • 1
    Right, right, "In your second example, though, you're simply requiring that the dictionary key be Hashable, not that all keys be the same concrete type.". Thanks! – Srđan Rašić Jan 14 '15 at 15:19