Returning a protocol with associatedtype from another protocol API

Viewed 23

I have a Session protocol with an Output associated type:

public protocol SessionAPI {
  associatedtype Output: Equatable
  var output: Output { get }
}

And a concrete implementation of the protocol that returns a String:

public final class StringSession: SessionAPI {
  public typealias Output = String
  public let output: String
}

Let's assume that the implementation of StringSession is very complex and touches many modules, and I don't want to add dependencies to those modules in classes that use the SessionAPI. So I have another protocol that vends StringSessions using a generic factory method:

public protocol SessionFactoryAPI {
  func createStringFactory<T: SessionAPI>() -> T where T.Output == String
}

All of this compiles fine. However, when I try to implement the factory API, I get a compilation error:

public final class SessionFactory: SessionFactoryAPI { public func createStringFactory<T: SessionAPI>() -> T where T.Output == String { // Error: Cannot convert value of type 'StringSession' to expected argument type 'T' return StringSession() } }

Does anyone have any suggestions on how to get this to work?

0 Answers
Related