我定义了一个协议(protocol):
protocol Usable {
func use()
}
和一个符合该协议(protocol)的类
class Thing: Usable {
func use () {
println ("you use the thing")
}
}
我想以编程方式测试 Thing 类是否符合 Usable 协议(protocol)。
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
添加到协议(protocol)中并得到错误
Forced downcast in conditional binding produces non-optional type 'Usable'
在 as
之后添加 ?
,最终修复了错误。
如何使用非@objc 协议(protocol)的条件绑定(bind)实现此功能,与“Advanced 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")
}
关于protocols - 条件绑定(bind)中的绑定(bind)值必须是可选类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111009/