Vasyl Khmil Vasyl Khmil - 5 months ago 15x
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.


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.