Creating a "generated" number from an NSString

86 Views Asked by At

I'm trying to find a way that I can turn any string into a generated, deterministic number.

That is...

  1. Each time that the same string is used it will create the same number.
  2. Different strings will (probably) create different numbers.

For instance, you could add the letter indices in the alphabet for each letter in the string.

Of course, this wouldn't work for strings in languages that don't use the same alphabet.

There must be a better way to get something like that to work though?

2

There are 2 best solutions below

1
On BEST ANSWER

NSObject has a method called "hash" that will do this for you: NSObject hash

in ObjectiveC:

NSUInteger value = myString.hash;

in Swift:

let value = myString.hash
2
On

You can use NSString.hash, or yes, other languages' characters are also represented by numbers: if you don't mind the size, you can contact them. Base64 also creates (hexadecimal) numbers from strings.