簡體   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