“枚举大小写的原始值不是唯一的”对于Swift枚举与浮点原始值 [英] "Raw value for enum case is not unique" for Swift enum with Float raw values

查看:440
本文介绍了“枚举大小写的原始值不是唯一的”对于Swift枚举与浮点原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Swift编程语言,我应该能够创建具有字符串,字符或任何整数或浮点数类型的原始值的Swift枚举。但是当我尝试:

 枚举BatteryVoltage:Float {
case v3v7 = 3.7
case v5v0 = 5.0
case v7v4 = 7.4
case v11v1 = 11.1
case v12v0 = 12.0
}

...我收到一个编译错误:

 枚举大小写的原始值不唯一$ v7v4行上的b $ b  

。它被编译为罚款,那个被评论了。但是啊,对我来说看起来是独一无二的。如果我的值为7.41,或7.3或其他东西编译正确。这是怎么回事? Swift bug?

解决方案

它绝对说你可以,但不要使用浮点值(特别是 Float )你需要比较平等 - 精确度不能保证足够好。并且始终使用 Double ,除非您绝对需要使用 Float 。出于兼容性原因,



在这种情况下,似乎有麻烦,因为(a)第三种情况是第一种情况是2x,(b)我不知道的其他一些因素。使用 3.3 / 6.6 3.4 / 6.8 3.6 / 7.2 也给了我这个问题,但是$ code> 3.5 / 7.0 没有。然而,我可以通过将最后一个案例更改为 22.2 (2x 11.1 )来显示。



这是一个解决方法 - 使用典型的 Int 枚举,并提供一个 doubleValue property:

 枚举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
}
}
}

有一些枚举的好的附加功能,你可以利用它们的优势,如果它们是 Int b $ b

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?

解决方案

It definitely says you can, but don't use floating-point values (and especially Float) where you're going to need to compare equality -- the precision just isn't guaranteed to be good enough. And always use Double unless you absolutely need to use a Float for compatibility reasons.

In this case, it seems like it's having trouble because (a) the third case is 2x the first case, and (b) some other factor I don't know. Using 3.3/6.6, 3.4/6.8, and 3.6/7.2 also gave me the issue, but 3.5/7.0 did not. However, I could get it to show up by changing the last case to 22.2 (2x 11.1).

Here's a workaround — use a typical Int-based enumeration, and provide a 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 some nice additional features of enums you can take advantage of if they're Int-based.

这篇关于“枚举大小写的原始值不是唯一的”对于Swift枚举与浮点原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆