Why the swift enum is returning wrong hashValue in swift 4.1?

1.1k views Asked by At

I have an enum as below

enum LoginItems: Int {
    case email = 0
    case password
    case login

    static let numberOfItems = LoginItems.login.hashValue + 1
}

Previously in xcode 9.3 we were using swift 4.0 and it used to give proper value but now it gives the value as 5364119284923175996 which is totally wrong. Can someone tell me what is wrong with swift 4.1 or am I doing something wrong in the code.

1

There are 1 answers

3
Rakesha Shastri On

You seem to have confused rawValue with hashValue.

enum LoginItems: Int {
    case email = 0
    case password
    case login

    static let numberOfItems = LoginItems.login.rawValue + 1
}

And your code would not have worked in any version of Swift. Because rawValue is not the same as hashValue. An even better solution has come up in Swift 4.2 which is CaseIterable protocol which gives you all the cases as an array.

enum LoginItems: CaseIterable {
    case email
    case password
    case login
}

In this case you wouldn't even need a static variable.

print(LoginItems.allCases.count)