How does one generate a random number in Apple's Swift language?

后端 未结 25 1559
有刺的猬
有刺的猬 2020-11-22 09:51

I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation in one\'s own program? Or is t

相关标签:
25条回答
  • The following code will produce a secure random number between 0 and 255:

    extension UInt8 {
      public static var random: UInt8 {
        var number: UInt8 = 0
        _ = SecRandomCopyBytes(kSecRandomDefault, 1, &number)
        return number
      }
    }
    

    You call it like this:

    print(UInt8.random)
    

    For bigger numbers it becomes more complicated.
    This is the best I could come up with:

    extension UInt16 {
      public static var random: UInt16 {
        let count = Int(UInt8.random % 2) + 1
        var numbers = [UInt8](repeating: 0, count: 2)
        _ = SecRandomCopyBytes(kSecRandomDefault, count, &numbers)
        return numbers.reversed().reduce(0) { $0 << 8 + UInt16($1) }
      }
    }
    
    extension UInt32 {
      public static var random: UInt32 {
        let count = Int(UInt8.random % 4) + 1
        var numbers = [UInt8](repeating: 0, count: 4)
        _ = SecRandomCopyBytes(kSecRandomDefault, count, &numbers)
        return numbers.reversed().reduce(0) { $0 << 8 + UInt32($1) }
      }
    }
    

    These methods use an extra random number to determine how many UInt8s are going to be used to create the random number. The last line converts the [UInt8] to UInt16 or UInt32.

    I don't know if the last two still count as truly random, but you can tweak it to your likings :)

    0 讨论(0)
提交回复
热议问题