我有一个协议定义:
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)