简体   繁体   English

我在 Swift 中的通用协议有什么问题?

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

Couldn't get my head around how protocol generic types work in Swift.无法理解协议泛型类型在 Swift 中是如何工作的。 Same solution in Java or Kotlin would work without problems. 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() {}
}

I get 2 errors in my code.我的代码中有 2 个错误。 First one is when I put where generic constraint on another protocol第一个是当我将通用约束放在另一个协议上时类型约束错误

Second error is that my Interactor class doesn't conform to the protocol.第二个错误是我的 Interactor 类不符合协议。 When I click fix it will add another 'typealias T = type' and want me specify T again.当我单击修复时,它将添加另一个“typealias T = type”并希望我再次指定 T。 交互器不符合协议

I want to know if there is another way to achieve this in Swift or how to fix this problem.我想知道是否有另一种方法可以在 Swift 中实现此目的或如何解决此问题。 Idea behind this is to extend my interactor classes with generic property result which is used as delegate for other layers.这背后的想法是使用通用属性结果扩展我的交互器类,该属性结果用作其他层的委托。 Interactor is used via his protocol and it's injected in all other classes. Interactor 是通过他的协议使用的,它被注入到所有其他类中。

As @vadian comment says: "The type of the typealias must be a concrete type, not a protocol".正如@vadian 评论所说:“类型别名的类型必须是具体类型,而不是协议”。 But if you want this class to be used with different InteractorResultProtocol then you can use generic for Interactor class also.但是,如果您希望此类与不同的 InteractorResultProtocol 一起使用,那么您也可以对 Interactor 类使用泛型。 And define T later.并稍后定义 T。

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

Usage:用法:

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