Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an optional protocol method?

Tags:

swift

I have a class that conforms to my own protocol that has optional methods. The reference to that class's object is also an optional. In other words, the object may be present and it may have implemented the method in question. But how do I call it? I have code like this:

if let theDelegate = delegate {
    if let result = theDelegate.delegateMethod() {
    }
}

but Xcode complains that the "value of optional type '(()->())?' not unwrapped". it wants me to change the second half of line 2 in the example to "theDelegate.delegateMethod!()", but force unwrapping defeats the purpose of what I am trying to do. How am I supposed to call this method? Note that my method has no parameters or return values.

like image 354
PopKernel Avatar asked Aug 19 '15 16:08

PopKernel


1 Answers

According to the documentation, optional methods should be called like this:

if let theDelegate = delegate {
    if let result = theDelegate.delegateMethod?() {
    }else {
        // delegateMethod not implemented
    }
}

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.

like image 80
Tamás Zahola Avatar answered Nov 15 '22 08:11

Tamás Zahola