I've been reading documentation about String.hashCode() on http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java Trying obtain an identical result from an identical string, but I did not come up with any satisfying results. In Objective-C [NSString hash] gives a totally different result.
Have anyone already done this?
Thanks
I made an efficient snippet that mimic the Java string.hashCode() result using the math algorithm at the wiki page: http://en.wikipedia.org/wiki/Java_hashCode%28%29#The_java.lang.String_hash_function
}
hope it help someone! Keep in mind, as commented by Chris, that if the Java string.hashCode() algorithm is rewritten problems may occur.
The answer provided by Alfred is not correct. First of all, hashCode can return negative, so the return type should be a signed integer and not an unsigned integer. Secondly, the charAsciiValue++ is off. In the original Java code, an array index is being incremented, not a unichar. Here is a tested/working version that's a category on NSString:
Edit: I originally used NSInteger, but I ran into issues with it. I believe it was due to the machine being 64 bit. Switching NSInteger to int fixed my issue.
Updated code for swift 4