A type that provides uniformly distributed random data.


When you call methods that use random data, such as creating new random values or shuffling a collection, you can pass a RandomNumberGenerator type to be used as the source for randomness. When you don’t pass a generator, the default Random type is used.

When providing new APIs that use randomness, provide a version that accepts a generator conforming to the RandomNumberGenerator protocol as well as a version that uses the default generator. For example, this Weekday enumeration provides static methods that return a random day of the week:

enum Weekday: CaseIterable {
    case sunday, monday, tuesday, wednesday, thursday, friday, saturday

    static func random<G: RandomNumberGenerator>(using generator: inout G) -> Weekday {
        return Weekday.allCases.randomElement(using: &generator)!

    static func random() -> Weekday {
        return Weekday.randomWeekday(using: &Random.default)

Conforming to the RandomNumberGenerator Protocol

A custom RandomNumberGenerator type can have different characteristics than the default Random type. For example, a seedable generator can be used to generate the same sequence of random values for testing purposes.

To make a custom type conform to the RandomNumberGenerator protocol, implement the required next() method. Each call to next() must produce a uniform and independent random value.

Types that conform to RandomNumberGenerator should specifically document the thread safety and quality of the generator.


Instance Methods

func next() -> UInt64

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

Required. Default implementation provided.

func next<T>(upperBound: T) -> T

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


Adopted By

See Also

Random Number Generators

struct Random

The default source of random data.


Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software