簡體   English   中英

我在 Swift 中的通用協議有什么問題?

[英]What is the problem with my generic protocol in Swift?

無法理解協議泛型類型在 Swift 中是如何工作的。 Java 或 Kotlin 中的相同解決方案可以毫無問題地工作。

protocol ResultProtocol {
   associatedtype T: ResultTypeProtocol
   var result: T? { get set }
}

protocol ResultTypeProtocol {
   func didGet()
}


protocol InteractorProtocol: ResultProtocol where T == InteractorResultProtocol {
   func someLogicRelatedToInteractor()
}

protocol InteractorResultProtocol: ResultTypeProtocol {
   func interactorResult()
}

class Interactor: InteractorProtocol {
  typealias T = InteractorResultProtocol

  var result: InteractorResultProtocol?

  func someLogicRelatedToInteractor() {}
}

我的代碼中有 2 個錯誤。 第一個是當我將通用約束放在另一個協議上時類型約束錯誤

第二個錯誤是我的 Interactor 類不符合協議。 當我單擊修復時,它將添加另一個“typealias T = type”並希望我再次指定 T。 交互器不符合協議

我想知道是否有另一種方法可以在 Swift 中實現此目的或如何解決此問題。 這背后的想法是使用通用屬性結果擴展我的交互器類,該屬性結果用作其他層的委托。 Interactor 是通過他的協議使用的,它被注入到所有其他類中。

正如@vadian 評論所說:“類型別名的類型必須是具體類型,而不是協議”。 但是,如果您希望此類與不同的 InteractorResultProtocol 一起使用,那么您也可以對 Interactor 類使用泛型。 並稍后定義 T。

class Interactor<ResultProtocolType: InteractorResultProtocol>: InteractorProtocol {
    typealias T = ResultProtocolType
    var result: ResultProtocolType?
    func someLogicRelatedToInteractor() {}
}

用法:

struct MyInteractorResultProtocol: InteractorResultProtocol {
    func interactorResult() {}
    func didGet() {}
}
let interactor = Interactor<MyInteractorResultProtocol>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM