Johnston
Johnston

Reputation: 20884

Checking for optional protocol methods in Swift gives error?

After reading the Apple docs on optional protocol requirements it says you can use optional chaining to check for the implementation. I tried this out and I keep getting an error. It seems like this is no longer a valid way of doing this and I am trying to find out if there is a new way to do this now.

Here is a example so you can see the error: http://swiftstub.com/743693493/
Here is my code:

@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:Bear?
    func scareBears() {
        if let cough = bear?.cough?() {
            println(cough)      
        } else {
            println("bear was scared")  
        }
    }
}

I get the error: error: 'Bear' does not have a member named 'cough' if let cough = bear?.cough?() {

Upvotes: 2

Views: 415

Answers (1)

Mike S
Mike S

Reputation: 42325

The error you're getting makes sense because Swift can know at compile time that Bear doesn't implement cough() (whereas Objective-C wouldn't necessarily be able to know that).

To make your code compile, you need to define bear using the Bearable protocol instead of the Bear class.

var bear: Bearable?

Which is probably what you'd want anyway. Otherwise, there's not much point in creating that protocol.

Upvotes: 5

Related Questions