protocols - 条件绑定(bind)中的绑定(bind)值必须是可选类型

标签 protocols swift conditional-binding

我定义了一个协议(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/

相关文章:

c - 如何将数组拆分为特定大小

ios - 如何在同一张图片的多种尺寸上实现相同的 CIFilter 效果

c# - 如何有条件地绑定(bind)数据?

swift - 在 Swift 中,当协议(protocol)被限制为从类继承时会发生什么?

HTTP:非法分块编码

protocols - 在 ClojureScript 中扩展协议(protocol)以从 native js 对象中获取值

ios - swift 中的 Dynamic Cast Class Unconditional 问题

ios - 在 TableView 单元格中显示来自 Firebase 的数据

swift - 有条件地绑定(bind)到现有属性