Srđan Rašić
Srđan Rašić

Reputation: 1787

When to use Type Constraints in Swift?

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.

Upvotes: 1

Views: 818

Answers (1)

NRitH
NRitH

Reputation: 13893

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.

Upvotes: 4

Related Questions