简体   繁体   中英

What is the problem with my generic protocol in Swift?

Couldn't get my head around how protocol generic types work in Swift. Same solution in Java or Kotlin would work without problems.

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. 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. When I click fix it will add another 'typealias T = type' and want me specify T again. 交互器不符合协议

I want to know if there is another way to achieve this in Swift or how to fix this problem. 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.

As @vadian comment says: "The type of the typealias must be a concrete type, not a protocol". But if you want this class to be used with different InteractorResultProtocol then you can use generic for Interactor class also. And define T later.

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>()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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