NumericAnnex Reference (100% documented)

View on GitHub

Install in Dash

Random

public final class Random : PRNG

A pseudo-random number generator (PRNG) that implements xorshift128+, an efficient linear-feedback shift register.

Warning

Once seeded from cryptographically secure random bytes, an instance of Random generates high-quality random numbers but is not a cryptographically secure PRNG.

To generate random numbers, create your own instance of Random with an internal state seeded from cryptographically secure random bytes:

let random = Random()!
let x = random.uniform() as Int

// You can also pass the desired result type as an argument.
let y = random.uniform(Int.self)

if x > y {
  print("Here's a random value between 0 and 42 (inclusive):")
  print(random.uniform(a: 0, b: 42))
} else {
  print("Here's a random value between -42 and 0 (inclusive):")
  print(random.uniform(a: -42, b: 0))
}
Topics
  • state

    The internal state of the pseudo-random number generator.

    Declaration

    Swift

    public var state: (UInt64, UInt64)
  • init(state:)

    Creates a pseudo-random number generator with the given internal state.

    Declaration

    Swift

    public init(state: (UInt64, UInt64))
    Parameters
    state

    The value to be used as the generator’s internal state.

  • init()

    Creates a pseudo-random number generator with an internal state seeded using cryptographically secure random bytes.

    If cryptographically secure random bytes are unavailable, the result is nil.

    Declaration

    Swift

    public convenience init?()
  • next()

    Declaration

    Swift

    public func next() -> UInt64?
  • Xoroshiro

    A pseudo-random number generator (PRNG) that implements xoroshiro128+, a successor to xorshift128+ devised by S. Vigna and D. Blackman.

    Warning

    Once seeded from cryptographically secure random bytes, an instance of Random.Xoroshiro generates high-quality random numbers but is not a cryptographically secure PRNG.

    To generate random numbers, create your own instance of Random.Xoroshiro with an internal state seeded from cryptographically secure random bytes:

    let random = Random.Xoroshiro()!
    let x = random.uniform() as Int
    
    // You can also pass the desired result type as an argument.
    let y = random.uniform(Int.self)
    
    if x > y {
      print("Here's a random value between 0 and 42 (inclusive):")
      print(random.uniform(a: 0, b: 42))
    } else {
      print("Here's a random value between -42 and 0 (inclusive):")
      print(random.uniform(a: -42, b: 0))
    }
    

    See also

    Random, PRNG
    See more…
    Declaration

    Swift

    public final class Xoroshiro : PRNG