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

50,566

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>()
}
Share:
50,566
devios1
Author by

devios1

I am a coder: an architect of thought. My name is Logan. I am the founder and sole employee of The Little Software Company. My current project is developing a textual layout language to replace Auto Layout and Interface Builder (ambitious huh?). I'm currently working for Quetzal POS on our next-gen iPad based point of sale.

Updated on February 22, 2020

Comments

  • devios1
    devios1 over 4 years

    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>()
    
  • devios1
    devios1 almost 10 years
    ...because the compiler has to ensure it's the same type on either side, but the protocol only ensures it meets the contract. I see. Still, it seems like Equatable ought not to necessarily imply Equatable since that's not strictly necessary to generate a hash code.
  • devios1
    devios1 almost 10 years
    Oh no wait it does, because Dictionary needs to be able to know if a given object is indeed the correct key, because it's possible for two different objects to generate the same hash code. Hmm, that is a bit tricky. So the problem here is really with Equatable.
  • finneycanhelp
    finneycanhelp over 8 years
    Look at 0:56 into the great presentation by Alexis Gallagher titled: Protocols with Associated Types and how they got that way (maybe) youtu.be/XWoNjiSPqI8
  • devios1
    devios1 over 8 years
    @finneycanhelp Thanks for this 👍👍. Great video!
  • Era
    Era over 3 years
    Swift is truly one of the most poorly designed languages I have ever seen...