Search code examples
swiftgenericsswift-protocols

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


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>()

Solution

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

    static 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: