PopKernel
PopKernel

Reputation: 4260

How to call an optional protocol method?

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.

Upvotes: 7

Views: 2644

Answers (1)

Tamás Zahola
Tamás Zahola

Reputation: 9321

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.

Upvotes: 10

Related Questions