2

Let's assume I have five UIView objects which all conform to a particular protocol. I have an object which should maintain a list of these objects, and message them all when necessary.

protocol MyProtocol: AnyObject {
    func doSomething()
}

The problem is, when I go to add these UIViews to a Set variable, the compiler produces an error because MyProtocol does not conform to Hashable. I can understand the reasoning for this, can anyone think of good ways to overcome this? In the meantime I considered using NSHashTable instead, but you lose the nice enumeration features of Sets.


Updating answer to post some sample code (this is still not working)

protocol MyProtocol: class, AnyObject {
    func doSomething()
}

class MyClass {
    var observers: Set<MyProtocol> = Set<MyProtocol>()
}
Ricky
  • 3,101
  • 1
  • 25
  • 33
  • What have you done that it says you should implement Hashable ? The code that you have listed is fine. It has no constraint to Hash. – Sandeep Jun 17 '15 at 06:00

1 Answers1

0

As you are defining protocol for class so you need to write 'class' keyword before inheriting any other protocol:

    protocol MyProtocol: AnyObject, Hashable{
         func doSomething()
    }


    class MyClass<T: MyProtocol> {

         var observers: Set<T> = Set<T>()
    }

Change your protocol to this and it will work fine. You can refer Apple Documentation for further details.

Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57