According to The Swift Programming Language, I should be able to create a Swift enum with raw values of "strings, characters, or any of the integer or floating-point number types". But when I try:
enum BatteryVoltage: Float {
case v3v7 = 3.7
case v5v0 = 5.0
case v7v4 = 7.4
case v11v1 = 11.1
case v12v0 = 12.0
}
... I get a compilation error:
Raw value for enum case is not unique
on the v7v4 line. It compiles fine with that one commented out. But ah, it looks unique to me. If I make the value 7.41, or 7.3 or something else it compiles fine. What's going on? Swift bug?
(From my above comment:)
That looks definitely like a bug. It seems to happen if one enum value is exactly equal to "2 times another enum value", but not equal to an integer.
More generally (as @Sulthan observed) the error occurs if the ratio of the enumeration
values is a power of two, such as 3.7/7.4
, 1.2/4.8
, or 1.1/17.6
, but only
if both values have a non-zero fractional part. So 1.5/3.0
or 1.25/5.0
do not
cause an error.
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