127
votes

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>()
2
@jtbandes That's not a duplicate. I'm asking what the error message actually means. What is a "Self or associated type requirement"?devios1

2 Answers

94
votes

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.

12
votes

To solve this you could use generics. Consider this example:

class GenericClass<T: Observing> {
   var observers = HashSet<T>()
}