Reading time: 1 min

This quick recipe shows how to write an extension for a Combine Publisher whose output is of a generic type.

Say you have a simple generic enum:

public enum AsyncState<Value> {
  case idle,
       loading,
       ready(Value),
       failure(Error)
}

If you wish to write an extension for a Publisher that produces AsyncState values, you might encounter the following error:

Screenshot%202022-05-09%20at%2008.06.22

The solution is to specify the Output constraint in the where of the extension function:

public extension Publisher {
  func mapAsyncState<OldValue, NewValue>(
    _ transform: @escaping (OldValue) async throws -> NewValue
  ) -> some Publisher
  where Output == AsyncState<OldValue> { // HERE
    // your implementation
  }

Next Post Previous Post