3

What is the best way to call optional delegate functions in Swift?

Suppose that I have the following protocol:

@objc protocol SomeDelegate {

    optional func someOptionalFunction(sender: AnyObject)

}

and I have the class that looks like this:

class Foo {

    var delegate: SomeDelegate! = nil

    func someFunction(email: String, password: String) {
        self.delegate.someOptionalFunction?(self)
    }

}

Should I call it like this or not? If not, what is the best practice to do it?

Thanks in advance.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • the [optional chaining](https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/OptionalChaining.html) is one of the most common patterns in swift, so, IMHO you are doing this in the right way – tkanzakic Nov 25 '14 at 09:53

2 Answers2

2

The "?" bit in that call is what makes it safe to call, whether the optional delegate is implemented or not. That's all I would do in my own code.

If you absolutely wanted to be certain someOptionalFunction exists, you could always use respondsToSelector, which exists for every NSObject instance. But it's almost certainly overkill.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • While the question mark-after-method-name is described in "Using Swift with Cocoa and Objective-C" I can't find documentation on this in "The Swift Programming Language". Do you, by chance, have a reference? – Nikolai Ruhe Nov 25 '14 at 10:23
  • [Here's the "Optional Chaining" section of Apple's Swift Programming language doc](https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/OptionalChaining.html#//apple_ref/doc/uid/TP40014097-CH21-XID_368). I think what you're asking for is the "Calling Methods Through Optional Chaining" bit? – Michael Dautermann Nov 25 '14 at 10:40
  • Yeah, I've been looking at exactly this piece. But I can't find any mention of the `method?()` call syntax wich dynamically checks if the method is implemented. – Nikolai Ruhe Nov 25 '14 at 10:51
  • @NikolaiRuhe here it is: https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-XID_6 – rintaro Nov 25 '14 at 11:14
  • @rintaro Thanks, but I was looking for a proper documentation of the feature (in the Swift book). I wan't to know the name of the feature and if it's considered a part of optional chaining. – Nikolai Ruhe Nov 25 '14 at 11:40
1

someOptionalFunction?(self) is absolutely OK. but...

Basically, the reference to the delegate should be weak and Optional.

class Foo {

    weak var delegate: SomeDelegate? = nil
//  ^^^^                           ^  
    func someFunction(email: String, password: String) {
        self.delegate?.someOptionalFunction?(self)
//                   ^
    }
}
rintaro
  • 51,423
  • 14
  • 131
  • 139