ios - 具有关联类型的 Swift 协议(protocol)中的弱属性要求

标签 ios swift

我想编写一个属性要求较弱的协议(protocol)。符合它的类必须能够为此属性指定任何类型。此外,我不想指定实际类型,因此它应该是使用某种协议(protocol)指定的类型。这段代码展示了我对非弱属性的想法:

protocol ObjectProtocol: class {
  typealias PropertyType
  var property: PropertyType {get set}
}

protocol FirstPropertyProtocol: class {}
protocol SecondPropertyProtocol: class {}

class FirstObjectImpl: ObjectProtocol {
  var property: FirstPropertyProtocol?
}

class SecondObjectImpl: ObjectProtocol {
  var property: SecondPropertyProtocol?
}

它按预期工作。

我尝试对弱属性做同样的事情:

protocol ObjectProtocol: class {
  typealias WeakPropertyType: AnyObject //must be a class type
  weak var weakProperty: WeakPropertyType? {get set}
}

protocol WeakPropertyProtocol: class {}

class ObjectImpl: ObjectProtocol {
  weak var weakProperty: WeakPropertyProtocol?
}

我得到一个编译器错误:

Type 'ObjectImpl' does not conform to protocol 'ObjectProtocol'

我有什么办法可以让它工作吗?

最佳答案

我让它与 WeakPropertyProtocol 的 @objc 属性一起工作:

protocol ObjectProtocol: class {
  typealias WeakPropertyType: AnyObject //must be a class type
  weak var weakProperty: WeakPropertyType? {get set}
}

@objc protocol WeakPropertyProtocol {}

class SomeObjectImpl: ObjectProtocol {
  weak var weakProperty: WeakPropertyProtocol?
}

这不是最佳解决方案,因为我担心来自 apple doc 的这条注释

Note also that @objc protocols can be adopted only by classes that inherit from Objective-C classes or other @objc classes.

我可以忍受这个限制,但我会感谢任何更好的解决方案。

关于ios - 具有关联类型的 Swift 协议(protocol)中的弱属性要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35755286/

相关文章:

objective-c - 无法构建 Objective-c 模块?

ios - 使用 CoreData 保存用户文章 - 如何让所有文章都保存在 UITableView 中?

ios - 无法在 opengl es 2.0 中加载多个纹理

javascript - iOS 不更新 JavaScript 文件

swift - 奥特莱斯与奥特莱斯系列

ios - 从 UITableViewCell 到 ViewController 的按钮操作

ios - 可选<String>到Int64为零,硬编码它可以工作

ios - Objective-C NSArray、 block 、STAsertEquals

swift - iPhone 和 Watch 之间共享数据的 App Group 孤儿功能

ios - swift 默认自动释放吗?应用空闲时内存增长的原因是什么?