ios - 初始化的枚举返回错误的 hashValue

标签 ios swift enums

这是 Swift 1.2,我使用的是 Xcode 6.4。以下枚举具有可失败的初始化程序。

enum EstimateItemStatus: Int, Printable {
    case Pending = 1
    case OnHold = 2
    case Done = 3

    var description: String {
        switch self {
        case .Pending: return "Pending"
        case .OnHold: return "On Hold"
        case .Done: return "Done"
        }
    }

    init?(id : Int) {
        switch id {
        case 1:
            self = .Pending
        case 2:
            self = .OnHold
        case 3:
            self = .Done
        default:
            return nil
        }
    }
}

如果我传递一个 ID 并初始化一个实例,我得到的枚举值是正确的。但是 hashValue 是错误的。例如,

let status = EstimateItemStatus(id: 2)!
println("\(status.hashValue) - \(status)")

我得到的输出是1 - On Hold

但它应该是 2 - On Hold。

我在这里做错了什么?这是编译器错误还是我遗漏了什么?

Demo playground

最佳答案

也许您混淆了 hashValuerawValue
哈希值不强制等于原始值

关于ios - 初始化的枚举返回错误的 hashValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33387336/

相关文章:

ios - NSUrlSession 不工作

ios - 用户注销时清除钥匙串(keychain)中的值

ios - 在 Swift 中观察 ObjC 类的属性

c# - 引用外部类型枚举和包含方法

iphone - 在 UIPageViewController 中禁用/启用滚动

ios - 模型类 Swift 中的完成处理程序

ios - 使用 'case let x = y as NSString 发生内存泄漏

ios - 当我回到包含 ARSCNView 的 View Controller 时,相机卡住。如何在 ARSCNView 停止工作的情况下进入和离开这个 View Controller ?

java - 通过其内部字段获取枚举

mysql - 如何在 SQL 中向枚举添加特定索引值,例如 enum ('a' =5 ,'b' ,c'=20)。有没有做这个的