Bound value in a conditional binding must be of Optional Type

前端 未结 5 555
你的背包
你的背包 2020-12-29 06:15

I have a protocol defined:

protocol Usable {
    func use()
}

and a class that conforms to that protocol

class Thing: Usabl         


        
相关标签:
5条回答
  • 2020-12-29 06:44

    As metioned in the Swift doc, the is operator is the guy you need for the job:

    The is operator checks at runtime to see whether the expression is of the specified type. If so, it returns true; otherwise, it returns false.

    The check must not be known to be true or false at compile time.

    Therefore, the following test would normally be what you need:

    if thing is Usable { 
        usableThing.use()
    } else {
        println("can't use that")
    }
    

    However, as the doc specifies, Swift can detect at compile time that the expression is always true and declares an error to help the developer.

    0 讨论(0)
  • 2020-12-29 06:51

    This works for me in the playground

    protocol Usable {
        func use()
    }
    
    class Thing: Usable {
        func use () {
            println ("you use the thing")
        }
    }
    
    let thing = Thing()
    let testThing : AnyObject = thing as AnyObject
    
    if let otherThing = testThing as? Thing {
        otherThing.use()
    } else {
        println("can't use that")
    }
    
    0 讨论(0)
  • 2020-12-29 06:54

    You can get it to compile by making the cast as Usable? instead of as Usable, like this:

    // Check whether or not a class is useable
    if let usableThing = thing as Usable? { // error here
        usableThing.use()
    }
    else {
        println("can't use that")
    }
    
    0 讨论(0)
  • 2020-12-29 07:00

    You are getting

    Bound value in a conditional binding must be of Optional Type
    

    because thing as Usable must return an optional type so making it as? should solved the problem. Unfortunately, the error still persisted for some odd reason. Anyway, a workaround I found to get it to work is to extract out the variable assignment inside the if statement

    let thing = Thing()
    
    let usableThing = thing as? Usable
    
    if useableThing { 
        usableThing!.use()
    }
    else {
        println("can't use that")
    }
    
    0 讨论(0)
  • 2020-12-29 07:01

    swift protocols does not work in Playgrounds in the first beta, try to build a real project instead.

    0 讨论(0)
提交回复
热议问题