"Original value for enumeration case is not unique" for Swift enumeration with Float raw values

According to the Swift Programming Language , I should be able to create a Swift enumeration with raw values ​​for strings, characters, or any integer or floating point type numbers. "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 line v7v4. It compiles great when commented on this. But ah, that looks unique to me. If I make the value 7.41, or 7.3, or something else, it compiles fine. What's happening? Quick mistake?

+8
enums swift
source share
3 answers

He definitely says that you can, but don’t use floating point values ​​(and especially Float ), where you will need to compare equality - accuracy is simply not guaranteed. And always use Double unless you need to use the Float parameter for compatibility reasons.

In this case, it seems that he has problems, because (a) the third case is equal to 2x of the first case, and (b) some other factor that I do not know. Using 3.3/6.6 , 3.4/6.8 and 3.6/7.2 also gave me a problem, but 3.5/7.0 did not. However, I could make it appear by changing the last case to 22.2 (2x 11.1 ).

Here's a workaround - use typical Int based numbering and provide the doubleValue property:

 enum BatteryVoltage: Int { case v3v7 case v5v0 case v7v4 case v11v1 case v12v0 var doubleValue: Double { switch self { case .v3v7: return 3.7 case .v5v0: return 5.0 case .v7v4: return 7.4 case .v11v1: return 11.1 case .v12v0: return 12.0 } } } 

There are a few additional additional enumeration options that you can use if they are Int based.

+7
source share

(From my comment above :)

It looks like an error. It seems that if one value of an enumeration is exactly equal to "2 times the other value of an enumeration", but not equal to an integer.

In general (as the Sultan noted), an error occurs if the ratio of the enumeration of the value is two, such as 3.7/7.4 , 1.2/4.8 or 1.1/17.6 , but only if both values ​​have a nonzero fractional part. So, 1.5/3.0 or 1.25/5.0 does not cause an error.

+4
source share

It worked for me.

I assigned an empty string to several register values ​​in the enumeration. I changed that. Make sure each register value is unique.

0
source share

All Articles