Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSHashTable to implement Observer pattern in Swift 3

Adding multiple delegates instead of only one is a quite common task. Suppose we have protocol and a class:

protocol ObserverProtocol
{
   ...
}

class BroadcasterClass
{
    // Error: Type 'ObserverProtocol' does not conform to protocol 'AnyObject'
    private var _observers = NSHashTable<ObserverProtocol>.weakObjects()
}

If we try to force ObserverProtocol to conform AnyObject protocol, we will get another error:

Using 'ObserverProtocol' as a concrete type conforming to protocol 'AnyObject' is not supported

Is it even possible to create a set of weak delegates in Swift 3.0?

like image 713
kelin Avatar asked Jan 26 '17 00:01

kelin


1 Answers

Sure, it's possible.

AnyObject is the Swift equivalent of id in Objective C. To get your code to compile, you just need to add the @objc annotation to your protocol, to tell Swift that the protocol should be compatible with Objective C.

So:

@objc protocol ObserverProtocol {

}
like image 179
Dave Weston Avatar answered Oct 14 '22 09:10

Dave Weston