Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift enum get the associated value of multiple case with same parameters in single switch-case

Tags:

ios

swift

Here is a common enum with associated values.

enum MultiplierType {
    case width(Double)
    case height(Double)
    case xxxxx1(Double)
    case xxxxx2(Double)
    case xxxxx3(Double)

    var value: Double {
        switch self {
            // Normal way.
            case let .width(value):
                return value
            case let .height(value):
                return value
            case let .xxxxx1(value):
                return value
            ...
        }
    }
}

My question is how to do like this?

var value: Double {
    switch self {
    // How to get the value in one case?
    case let .width(value), .height(value), .xxx:
         return value
    }
}

Or

var value: Double {
    switch self {
    // How to get the value in one case?
    case let .width, .height, .xxx (value):
         return value
    }
}

What is the most elegant way to get the associated value?

like image 300
Vincent Sit Avatar asked Aug 26 '18 21:08

Vincent Sit


1 Answers

You can put multiple enum values in the same case line, but you have to move the let into the ():

var value: Double {
    switch self {
    case .width(let value), .height(let value), .xxxxx1(let value):
         return value
    }
}

You might want to put each enum value on a separate line:

var value: Double {
    switch self {
    case .width(let value),
         .height(let value),
         .xxxxx1(let value):
         return value
    }
}

Unfortunately, that's about as elegant as it gets with enums with associated values. There's no way to get the associated value without explicitly listing the enums.

You can only combine values in the same line that have the same type of associated value, and all of the values have to bind to the same variable name. That way, in the code that follows, you know that the value is bound and what its type is no matter which enum pattern matched.

like image 132
vacawama Avatar answered Oct 06 '22 02:10

vacawama