-1

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.

Shreesha Kedlaya
  • 340
  • 4
  • 19
  • What value are you expecting? – Rakesha Shastri Sep 24 '18 at 09:18
  • 1
    What about using https://stackoverflow.com/questions/27094878/how-do-i-get-the-count-of-a-swift-enum ? – Larme Sep 24 '18 at 09:22
  • 2
    Why would you expect the `hashValue` to be consistent? Its documentation explicitly states that _"Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution."_. You shouldn't use that for any calculations. You should update to Swift 4.2 and use [CaseIterable](https://developer.apple.com/documentation/swift/caseiterable)'s `.allCases.count`. – Dávid Pásztor Sep 24 '18 at 09:22
  • Yes but before I was using hashvalue to get the count of the number of cases. We didn't have `allCases`. Can you post an answer @DávidPásztor. Thanks – Shreesha Kedlaya Sep 24 '18 at 09:26

1 Answers1

2

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)
vacawama
  • 150,663
  • 30
  • 266
  • 294
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
  • Previously using hashvalue used to give the position of the enum case and it was a perfect solution for getting the count of all the cases and it worked fine. Why did it change now @Rakesha Shastri? – Shreesha Kedlaya Sep 24 '18 at 09:45
  • @ShreeshaKedlaya I was not aware of that. My bad. This answer is what you seem to have applied. https://stackoverflow.com/a/27094973/7734643 Like the first comment says, it is an undocumented feature and to me it seems broken. – Rakesha Shastri Sep 24 '18 at 09:52
  • `hashValue` did indeed work in earlier versions of Swift, but it was an *invalid use* of `hashValue` and *should not* have been used. – vacawama Sep 24 '18 at 11:01