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 1:
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.
Solution 2:
To solve this you could use generics. Consider this example:
class GenericClass<T: Observing> {
var observers = HashSet<T>()
}