我定义了一个协议:
protocol Usable {
func use()
}
以及符合该协议的类
class Thing: Usable {
func use () {
println ("you use the thing")
}
}
我想以编程方式测试 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")
}
但我得到了错误
Bound value in a conditional binding must be of Optional Type
如果我尝试
let thing:Thing? = Thing()
我得到错误
Cannot downcast from 'Thing?' to non-@objc protocol type 'Usable'
然后我添加@objc
到协议并得到错误
Forced downcast in conditional binding produces non-optional type 'Usable'
此时我在?
之后添加as
,最终修复了错误。
如何通过非@objc 协议的条件绑定来实现此功能,与“Advanced Swift”2014 WWDC Video 中的相同?