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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With