Check out additional delegate methods with multiple arguments

New to Swift. Struggling with how to get the most concise / idiomatic syntax for calling an optional delegate method, if (a) a delegate is specified and (b) the method is implemented.

I know that ?this role can play (for example, self.delegate.foo?()), but I got stuck getting the syntax correctly when trying to call the ObjC delegate method, which has several arguments, and also returns the value (Bool), which I really like about capture (and I want to distinguish between "method not implemented" and "method implemented and returned false").

Here is an example. In this case, it MyDelegateProtocolhas an optional method -myThing:argTwo:argThree:(returns Bool).

This snippet seems to use semantics correctly, but it also uses respondsToSelectorvery chat. Is it possible to improve it more idiomatically?

if let delegate = self.delegate {
    if delegate.respondsToSelector(#selector(MyDelegateProtocol.myThing(_:argTwo:argThree:))) {
        if delegate.myThing!(self, argTwo: foo, argThree: bar) {
            // do something
        }
    }
}
+4
source share
1 answer

This code should work fine with options. And that’s all you need to write.

delegate?.myThing?(self, argTwo: foo, argThree: bar)

This code should handle all the cases that you tried to check, for example:

if let result = delegate?.myThing?(self, argTwo: foo, argThree: bar) {
     // "result" is the Bool returned from the method
}

, , . , , , Bool? ( ). , , - , . , , , , , , , .

+5

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


All Articles