Newish to Swift. Struggling with how to get the most concise/idiomatic syntax for calling an optional delegate method if (a) the delegate is set and (b) the method is implemented.
I know the ?
can play this role (eg self.delegate.foo?()
) but I'm stymied getting syntax right when trying to call an ObjC delegate method that has multiple arguments and also returns a value (Bool) that I care about capturing (and I want to distinguish between "method not implemented" and "method implemented and returned false").
Here's an example. In this case, MyDelegateProtocol
has an optional method -myThing:argTwo:argThree:
(returns Bool).
This snippet seems to get the semantics right, but it uses respondsToSelector
and is very chatty. Can it be improved in a more idiomatic way?
if let delegate = self.delegate {
if delegate.respondsToSelector(#selector(MyDelegateProtocol.myThing(_:argTwo:argThree:))) {
if delegate.myThing!(self, argTwo: foo, argThree: bar) {
// do something
}
}
}