Random

struct Random

The default source of random data.

When you generate random values, shuffle a collection, or perform another operation that depends on random data, this type's default property is the generator used by default. For example, the two method calls in this example are equivalent:

let x = Int.random(in: 1...100)
let y = Int.random(in: 1...100, using: &Random.default)

Random.default is automatically seeded, is safe to use in multiple threads, and uses a cryptographically secure algorithm whenever possible.

Platform Implementation of `Random`

While the Random.default generator is automatically seeded and thread-safe on every platform, the cryptographic quality of the stream of random data produced by the generator may vary. For more detail, see the documentation for the APIs used by each platform.

  • Apple platforms use arc4random_buf(3).
  • Linux platforms use getrandom(2) when available; otherwise, they read from /dev/urandom.
Inheritance RandomNumberGenerator View Protocol Hierarchy →
Import import Swift

Static Variables

static var `default`: Random

The default instance of the Random random number generator.

Declaration

static var `default`: Random { get set }

Instance Methods

mutating func next()

Returns a value from a uniform, independent distribution of binary data.

Returns: An unsigned 64-bit random value.

Declaration

mutating func next() -> UInt64

Declared In

Random, RandomNumberGenerator
mutating func next(_:)

Returns a random value that is less than the given upper bound.

upperBound: The upper bound for the randomly generated value. Returns: A random value of T in the range 0..<upperBound. Every value in the range 0..<upperBound is equally likely to be returned.

Declaration

mutating func next<T>(upperBound: T) -> T where T : FixedWidthInteger, T : UnsignedInteger

Declared In

RandomNumberGenerator