JuJ*_*oDi 19 protocols conditional-binding swift
我有一个协议定义:
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 protocol type 'Usable'
Run Code Online (Sandbox Code Playgroud)
然后我添加@objc到协议并得到错误
Forced downcast in conditional binding produces non-optional type 'Usable'
Run Code Online (Sandbox Code Playgroud)
在此?之后我添加了as,最终修复了错误.
如何通过使用非@objc协议进行条件绑定来实现此功能,与"高级Swift"2014 WWDC视频中的相同?
Con*_*nor 33
您可以通过将演员阵容设为可用来进行编译吗?而不是像我们这样可用:
// 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)
| 归档时间: |
|
| 查看次数: |
20587 次 |
| 最近记录: |