相关疑难解决方法(0)

条件绑定中的绑定值必须是可选类型

我有一个协议定义:

protocol Usable {
    func use()
}
Run Code Online (Sandbox Code Playgroud)

以及符合该协议的类

class Thing: Usable {
    func use () {
        println ("you use the thing")
    }
}
Run Code Online (Sandbox Code Playgroud)

我想以编程方式测试Thing类是否符合Usable协议.

let thing = Thing()

// Check whether or not a class is useable
if let usableThing = thing as Usable { // error here
    usableThing.use()
}
else {
    println("can't use that")
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误

Bound value in a conditional binding must be of Optional Type
Run Code Online (Sandbox Code Playgroud)

如果我试试

let thing:Thing? = Thing()
Run Code Online (Sandbox Code Playgroud)

我收到了错误

Cannot downcast from 'Thing?' to non-@objc …
Run Code Online (Sandbox Code Playgroud)

protocols conditional-binding swift

19
推荐指数
1
解决办法
2万
查看次数

标签 统计

conditional-binding ×1

protocols ×1

swift ×1