繁体   English   中英

具有关联类型的Swift协议中的弱属性要求

[英]Weak property requirement in Swift protocol with associated type

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

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?
}

我收到了一个编译器错误:

类型'ObjectImpl'不符合协议'ObjectProtocol'

有什么方法可以让我的工作吗?

我不相信协议可以强制执行弱点。 例如:

protocol ObjectProtocol: class {
  weak var weakProperty: AnyObject? {get set}
}

class ObjectImpl1: ObjectProtocol {
  weak var weakProperty: AnyObject?
}

class ObjectImpl2: ObjectProtocol {
  var weakProperty: AnyObject?
}

即使协议weak但ObjectImpl2没有实现它,这些都编译好了。

编辑:这是你想要的吗?...

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

protocol WeakPropertyProtocol: class {}

class ObjectImpl: ObjectProtocol {
  typealias WeakPropertyType = WeakPropertyProtocol
  weak var weakProperty: WeakPropertyProtocol?
}

此实现需要使用Any而不是AnyObject,因为WeakPropertyProtocol是一个协议而不是一个类。

或这个?...

protocol WeakPropertyProtocol: class {}

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

class MyWeakClass: WeakPropertyProtocol {

}

class ObjectImpl: ObjectProtocol {
  typealias WeakPropertyType = MyWeakClass
  weak var weakProperty: MyWeakClass?
}

无论哪种方式,我认为关键在于定义用于WeakPropertyType类/协议。

我使用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?
}

这不是最好的解决方案,因为我关注苹果doc的这个说明

另请注意,@ objc协议只能由继承自Objective-C类或其他@objc类的类采用。

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

Swift 4版。
我需要我的视图模型符合协议。 他们不能保留协调器对象:

protocol ViewModelType {
    associatedtype CoordinatorType: AnyObject
    weak var coordinator: CoordinatorType? { get }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM