繁体   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