I am creating an iOS version of an existing Android app. On the Android side, hashCode() of a String (username) is sent to the server and based on that hash, a JSON object is returned.
On Swift, I tried hash and hashValue properties but both of them produces values that are different from their Android counterpart.
So I decided to write my own implementation based on Java's implementation:
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
But when I write the above implementation in Swift, I get overflow crash. Can anybody help me here?
Thanks in advance.
Here is the Swift implementation:
I first had to write a Character extension that would return Ascii value of the character:
extension Character {
var asciiValue: UInt32? {
return String(self).unicodeScalars.filter{$0.isASCII}.first?.value
}
}
Then I created a String extension with: 1. a property that returns Ascii values of each character in the String. 2. a hash method to return the hash (copying the Java code)
extension String {
var asciiArray: [UInt32] {
return unicodeScalars.filter{$0.isASCII}.map{$0.value}
}
func myHash() -> Int {
var h = 0 as Int!
for i in 0..<asciiArray.count {
h = 31*h! + Int(array[i])
}
return h!
}
}
&+,&*, etc. exactly for this purpose.Hashablein Swift 3