Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if optional protocol method is implemented in Swift?

Tags:

ios

swift

I have a swift protocol:

@objc protocol SomeDelegate {

  optional func myFunction()

}

I one of my classes I did:

weak var delegate: SomeDelegate?

Now I want to check if the delegate has myFunction implemented.

In objective-c I can do:

if ([delegate respondsToSelector:@selector(myFunction)]) { 
...
}

But this is not available in Swift.

Edit: This is different from: What is the swift equivalent of respondsToSelector? I focus on class protocols not on classes.

How do I check if my delegate has an optional method implemented?

like image 530
confile Avatar asked May 22 '15 14:05

confile


2 Answers

Per The Swift Programming Language:

You check for an implementation of an optional requirement by writing a question mark after the name of the requirement when it is called, such as someOptionalMethod?(someArgument). Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented.

So the intention is not that you check whether the method is implemented, it's that you attempt to call it regardless and get an optional back.

like image 70
Tommy Avatar answered Nov 16 '22 13:11

Tommy


You can do

if delegate?.myFunction != nil {

}
like image 17
newacct Avatar answered Nov 16 '22 12:11

newacct