Back to Optional Protocol Requisites

With optional chaining tools in hand, you can now test to see whether your methods exist:

@objc protocol Bearable {    func growl()    optional func cough() -> String //Apparently bears cough when they are scared.}@objc class Bear:Bearable {    var name = "Black Bear"    func growl() {        println("Growllll!!!")    }}@objc class Forest {    var bear:Bearable?    func scareBears() {        if let cough = bear?.cough?() {            println(cough)        } else {            println("bear was scared")        }    }}var forest = Forest()forest.scareBears()

You check whether the Bearable implementation exists with optional chaining. You assign the return of the method with optional ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.