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?
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?
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)
    }
}