我想写一个弱性能需求的协议。符合它的类必须能够为该属性指定任何类型。另外我不想指定实际的类型,所以它应该是用某种协议指定的类型。此代码显示了我对非弱财产的想法:Swift协议中关联类型的弱性要求
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'
有没有什么办法可以使这项工作?
的问题是,协议不符合本身,而不是它从继承的任何协议,见http://stackoverflow.com/questions/33112559/protocol对于类似的问题,不符合自己。在你的情况下,WeakPropertyProtocol类型不符合AnyObject。 –
感谢您的评论,马丁。有没有其他的方式来指定我的'WeakPropertyType'是没有这个'AnyObject'约束的类类型? –
协议当前不需要将属性实现为弱存储属性。 https://stackoverflow.com/questions/47699813/weak-property-in-a-swift-protocol – Adobels