› Checking for the presence of an optional method in a protocol in Swift

Pretty cool.

import Foundation
 
@objc protocol Foo {
    optional func say() -> String
}
 
class Doesnt: NSObject, Foo {
}
 
class Does: NSObject, Foo {
    func say() -> String {
        return "hi"
    }
}
 
let doesnt: Foo = Doesnt()
let does: Foo = Does()
 
if let f = doesnt.say {
    f() // Never called
}
 
if let f = does.say {
    f() // Returns "hi"
}