swift - Swift 中的协议(protocol)向下转型

标签 swift

我遇到以下情况,我有一个通用协议(protocol) A,它可以有从它继承的变体(例如 B)和一个实现变体的类(C)。

protocol A {}

protocol B: A {
  var foo: String { get }
}

class C: B {
  let foo: String = "foo"
}

现在,如果我有一个 A 类型的对象,但实际上是一个 C,我怎样才能获得在 B 中声明的内容?

func foo() {
  let c: A = C()
}

如果我尝试像 let b = c as B 那样进行转换,我会得到 Cannot downcast from 'A' to non-@objc protocol type 'B'

最佳答案

您的代码看起来不错 - 唯一的问题是 as 运算符需要 objc 兼容性。您可以通过在协议(protocol)前添加 @objc 属性来修复此问题:

@objc protocol A {}

@objc protocol B: A {
    var foo: String { get }
}

不幸的是,这样做有一个缺点:你失去了使用 Objective C 中不可用的 swift 特定功能的能力,例如枚举、元组、泛型等。

更多信息请点击:Checking for Protocol Conformance

关于swift - Swift 中的协议(protocol)向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26760040/

相关文章:

ios - 无法将类型 'NSIndexPath' 的值转换为预期的参数类型 'NSIndexPath'

ios - 当我为我的 View 提供顶部边框时遇到问题

swift - 有序列表,其中项目相互不认识并按云中的属性排序 : How to avoid index changes in Cloud when user reorders?

ios - 如何将 UITableView 单元格设置为看起来像消息气泡?

swift - 如何以编程方式在 UIScrollView 中设置 StickyHeader

ios - 使用 parse.com 设置关注者列表的最佳方法是什么

ios - Swift 的 equatable 协议(protocol)一致性检查

ios - Swift NotificationCenter 删除观察者最快的方法

ios - 动画 subview

ios - swift 2 : My code saves the data(The item added shows in the list) but as soon as I force close the app it deletes all data?