'Unique Integer Value
I need a way to generate unique integer values in swift
//string
let g = NSUUID().UUIDString
How can I accomplish the above in int format?
Solution 1:[1]
Int(rand()) will give you random numbers, but not unique random numbers. Making them unique requires more work. If the set of numbers you want to draw from is small you can build a var array of numbers and remove one at a time randomly from the array.
The memory requirements of that get bad as the range of numbers gets large.
If you need a very large range of numbers but only need to generate a fairly small number of them you can add each number to a set of already-used numbers and then test each new number against the already-used numbers before returning it. That's fast and fairly memory-efficient until you generate thousands of unique numbers. It's memory requirements keep climbing. Sets test for membership quite fast, so that should be fine.
Can you give more details of your requirements?
Solution 2:[2]
Sounds like you just want a UUID value, or equivalent unique value, stored as an Int - which you can do with the built in hashValue method:
let g = UUID().hashValue
This method is deterministic so you'll always get the same resulting integer when supplying the same UUID.
Solution 3:[3]
If you would like to generate unique UInt value then this should work:
private static var counter: NSDecimalNumber = .zero
public static func uniqueUIntId() -> String {
counter = counter.adding(.one)
return counter.stringValue
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Duncan C |
Solution 2 | Gsp |
Solution 3 | Michal Zaborowski |