Jack
Jack

Reputation: 45

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 Error on type constraint

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. Interactor doesn't conform to protocol

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.

Upvotes: 0

Views: 645

Answers (1)

Samps
Samps

Reputation: 1049

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

Upvotes: 2

Related Questions