2

I am trying to use hashValue function for String in Swift. Unfortunately, the value returned isn't consistent and often is negative. Is this the expected behaviour?

How can I get a consistent Int value for a string in Swift?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
az2902
  • 418
  • 6
  • 18
  • 2
    What do you mean by "consistent"? And yes, negative values are normal. – rmaddy Mar 08 '19 at 05:38
  • 5
    From the [documentation](https://developer.apple.com/documentation/swift/hashable/1540917-hashvalue): “Hash values are not guaranteed to be equal across different executions of your program.” – Martin R Mar 08 '19 at 05:40
  • 1
    Related: https://stackoverflow.com/q/52440502/1187415, https://stackoverflow.com/q/35882103/1187415 – Martin R Mar 08 '19 at 05:43
  • The Option-click documentation for it says, "Summary An unsigned integer that can be used as a hash table address." If it's an unsigned integer, it should never be negative, but it is. – Victor Engel Aug 14 '22 at 15:06

1 Answers1

0

Swift 4 offers a new way that you can get hashes depending how you want. Just subscribe to Hashable protocol and implement hash(into hasher: inout Hasher) in your class:

class CustomClass:Equatable, Hashable {
    var id: Int32 = 0
    var name: String?

    init() {
    }



    static func == (lhs: CustomClass, rhs: CustomClass) -> Bool {
        return lhs.hashValue == rhs.hashValue
    }
    // hash value is calculated based on id, name parameters
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
        hasher.combine(name)
    }
}
Amir.n3t
  • 2,859
  • 3
  • 21
  • 28
  • 3
    That is correct, but it does not change the fact that the hash value changes with each program execution. It does not answer the question *“How can I get a consistent Int value for a string in Swift?”* – Martin R Mar 08 '19 at 06:26
  • 3
    You shouldn’t rely on specific hash values or save them across executions. On the rare occasion that you would need deterministic behavior, you can set the flag `SWIFT_DETERMINISTIC_HASHING` to disable random hash seeds. – Amir.n3t Mar 08 '19 at 09:24
  • where do I set SWIFT_DETERMINISTIC_HASHING? can. this be done in code for particular hashes? – ngb May 02 '22 at 09:39