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

SwiftGenericsXcode6Swift Protocols

Swift Problem Overview


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

Swift Solutions


Solution 1 - Swift

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 - Swift

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondevios1View Question on Stackoverflow
Solution 1 - SwiftnewacctView Answer on Stackoverflow
Solution 2 - Swiftph1lb4View Answer on Stackoverflow