我想编写一个属性要求较弱的协议(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/