我有一个协议定义: protocol Usable { func use()} 和符合该协议的类 class Thing: Usable { func use () { println ("you use the thing") }} 我想以编程方式测试Thing类是否符合可用协议。 let thing = Thing()// Che
protocol Usable { func use() }
和符合该协议的类
class Thing: Usable { func use () { println ("you use the thing") } }
我想以编程方式测试Thing类是否符合可用协议。
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'
在哪一点我添加?之后,最后修正了错误。
如何使用非@ objc协议的条件绑定来实现此功能,与“高级Swift”2014 WWDC视频相同?
您可以通过将该转换作为可用的方式来编译?而不是可用,像这样:// Check whether or not a class is useable if let usableThing = thing as Usable? { // error here usableThing.use() } else { println("can't use that") }