简体   繁体   中英

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

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?

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 enum s with associated values. There's no way to get the associated value without explicitly listing the enum s.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM