Swift: Random number for 64-bit integers?

后端 未结 4 1480
孤城傲影
孤城傲影 2020-12-03 11:11

So, with my current project, I need to work with 64-bit integers and I need to grab random numbers between ranges up to 100 billion. arc4random()/arc4random_uniform() only w

4条回答
  •  猫巷女王i
    2020-12-03 12:10

    Here is one neat solution! (methinks anyway, since I just made it up)

    let hex = UUID().uuidString.components(separatedBy: "-").suffix(2).joined()
    let rand = UInt64(hex, radix: 0x10)
    

    Quick test with Swift REPL:

    https://repl.it/GeIs/0

    for _ in 0..<5_000_000 {
        let hex = UUID().uuidString.components(separatedBy: "-").suffix(2).joined()
        set.insert(UInt64(hex, radix: 0x10)!)
    }
    set.count // prints 5_000_000
    

    As an extension...

    import Foundation
    
    
    extension UInt64 {
    
        static var random: UInt64 {
    
            let hex = UUID().uuidString
                .components(separatedBy: "-")
                .suffix(2)
                .joined()
    
            return UInt64(hex, radix: 0x10)!
        }
    }
    

提交回复
热议问题