Vasyl Khmil Vasyl Khmil - 1 year ago 80
Swift Question

Swift. How to get generic type from extension?

I'm trying to write extension to generic type, but for some reasons in is not working.

I've generic enum:

public enum ResponseResult<Result, Error> {

case Success(result: Result)
case Failure(error: Error?)

I want to write some extension to this enum and, for example create another generic class with enum generic params:

extension ResponseResult {

var response: Response<T> {
return Response(value: self.value)

T - is '
' generic parameter from
But I don't understand how can i fetch generic parameter in extension.

Answer Source

To extract the parameters from the enum values, you can use switch-case:

switch response {
case .Success(let result):
    print("Success: \(result)")
case .Failure(let error):
    print("Error: \(error)")

If you're inside an extension, simply replace response with self.

In your specific scenario, maybe this is what you're looking for:

extension ResponseResult {

    var response: Response<Result>? {
        switch self {
            case .Success(let result):
                return Response(value: result)
            case .Failure: // Ignore error parameter
                return .None

That pattern is very similar (exactly the same) to what Alamore uses for error handling. You can see their code and documentation for more samples.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download