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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With