A type that provides uniformly distributed random data.
SDK
- Xcode 10.0+
Framework
- Swift Standard Library
Declaration
protocol RandomNumberGenerator
Overview
When you call methods that use random data, such as creating new random values or shuffling a collection, you can pass a Random type to be used as the source for randomness. When you don’t pass a generator, the default System type is used.
When providing new APIs that use randomness, provide a version that accepts a generator conforming to the Random protocol as well as a version that uses the default system 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 {
        var g = SystemRandomNumberGenerator()
        return Weekday.random(using: &g)
    }
}
Conforming to the RandomNumberGenerator Protocol
A custom Random type can have different characteristics than the default System type. For example, a seedable generator can be used to generate a repeatable sequence of random values for testing purposes.
To make a custom type conform to the Random protocol, implement the required next() method. Each call to next() must produce a uniform and independent random value.
Types that conform to Random should specifically document the thread safety and quality of the generator.