Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can only be used as a generic constraint because it has self or associated?

Protocol can only be used as a generic constraint because it has Self or associatedType requirements.

What is generic protocol?

There are two ways to create a generic protocol - either by defining an abstract associatedtype or the use of Self (with a capital S). The use of Self or associatedtype is what we like to call "associated types". This is because they are only associated with the protocol they are defined in.

What is associated type?

What is an associated type? An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: it's a placeholder name of a type to use until the protocol is adopted and the exact type is specified.

What is type erasure Swift?

Type-erasure simply means "erasing" a specific type to a more abstract type in order to do something with the abstract type (like having an array of that abstract type). And this happens in Swift all the time, pretty much whenever you see the word "Any."


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.


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

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