kelin
kelin

Reputation: 11985

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?

Upvotes: 7

Views: 3701

Answers (1)

Dave Weston
Dave Weston

Reputation: 6635

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 {

}

Upvotes: 17

Related Questions