Using NSHashTable to Implement Observer Pattern in Swift 3

Adding multiple delegates instead of one is a fairly common task. Suppose we have a 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 get ObserverProtocol negotiate the AnyObject protocol, we get another error:

Using ObserverProtocol as a specific type matching the AnyObject protocol is not supported

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

+5
source share
1 answer

Of course available.

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

So:

 @objc protocol ObserverProtocol { } 
+7
source

Source: https://habr.com/ru/post/1263369/


All Articles