user11497206
user11497206

Reputation:

How to initialize generic enum using a protocol with associated type?

Consider the following definitions of an enum and a protocol

enum Result<T> {
    case success(info: T)
    case failure(message: String)
}

protocol Response {
    associatedtype T
    var info: T? { get }
}

I am trying to initialize a Result using a value that implements Response protocol.

The following code does not compile.

extension Result {
    init(response: Response) {
        // body of the initializer
    }
}

Can anyone point out how to solve this?

Upvotes: 0

Views: 202

Answers (1)

user28434&#39;mstep
user28434&#39;mstep

Reputation: 6600

Something like this:

extension Result {
    init<R: Response>(response: R) where R.T == T {
        if let info = response.info {
            self = .success(info: info)
        } else {
            self = .failure(message: "Whoops")
        }
    }
}

You can't use protocols-with-associated types directly, so you should use them as generic parameters.

Upvotes: 3

Related Questions