Swift Language Multicast Delegate

Swift : Create a multi-function multicast delegate

You need to change the signature of invokeDelegates to take a closure of type (MyProtocol) -> (), and then you need to pass each delegate to the closure.

protocol MyProtocol {
func method1()
func method2()
func method3()
}

class TestClass {
var delegates = [MyProtocol]()

func invokeDelegates(delegateMethod: (MyProtocol) -> ()) {
for delegate in delegates {
delegateMethod(delegate)
}
}
}

The closure should just invoke the appropriate delegate method on its argument. Swift can infer the argument and return types of the closure, and you can use the shorthand $0 to refer to the argument, so the closure can be quite short:

let tester = TestClass()
tester.invokeDelegates(delegateMethod: { $0.method1() })

On the other hand, you could just use Collection.forEach directly on the delegates array (if it's accessible) and skip the invokeDelegates method:

tester.delegates.forEach { $0.method1() }

Removing All instances of specific delegate from multicast delegates

Pretty self-explanatory:

outputProvider = (Func<int>) Delegate.RemoveAll(outputProvider, valueProvider3);

Multicast Delegate Ambigous

When you have a delegate that has multiple handlers attached to it, you will still get only one return value. There is no direct way to get the other values and naturally you cannot chain the handler functions in a way that the return value of one would be sent to another. The only thing you will get is the last attached handler's return value is returned.

There is no ambiguous behaviour here really, it's just the way it works. If you want to chain the functions you have to use a different approach then a delegate. In this example you could just call the functions and that's it.

xmppStreamDidConnect never gets called in Swift

As it is described in this Github Issue, the problem was the method declaration.
My xmppStreamDidConnect need an underscore, the root problem was that if you don't import the swift extensions the compiler marks that declaration as incorrect, although it works.
So to fix my problem, I need to import the pod 'XMPPFramework/Swift' and change the method declaration to

func xmppStreamDidConnect(_ sender: XMPPStream) {


Related Topics



Leave a reply



Submit