What does "Protocol ... can only be used as a generic constraint because it has Self or associated type requirements" mean?

devios1 picture devios1 · Jul 24, 2014 · Viewed 47.2k times · Source

I am trying to create a Dictionary (actually a HashSet) keyed on a custom protocol in Swift, but it is giving me the error in the title:

Protocol 'myProtocol' can only be used as a generic constraint because it has Self or associated type requirements

and I can't make heads nor tails of it.

protocol Observing: Hashable { }

var observers = HashSet<Observing>()

Answer

newacct picture newacct · Jul 25, 2014

Protocol Observing inherits from protocol Hashable, which in turn inherits from protocol Equatable. Protocol Equatable has the following requirement:

func ==(lhs: Self, rhs: Self) -> Bool

And a protocol that contains Self somewhere inside it cannot be used anywhere except in a type constraint.

Here is a similar question.