Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 146 ยท Standard Library and Foundation

Random Numbers

Generate random values in Swift - Int.random, randomElement, shuffled, SystemRandomNumberGenerator, and your own seeded RandomNumberGenerator for reproducible tests, simulations and games.

Random numbers drive dice rolls, shuffled playlists, test data, simulations, load balancing and procedural worlds. Swift builds good randomness into the standard library, with no import and no old C functions. A single idea runs through the whole API: every random method has a twin that takes using: and a generator. By default that generator is the system's secure one, but you can pass your own, and a generator you seed yourself produces the same "random" sequence every time. That is what makes random code testable.

This lesson covers the everyday methods, what happens when you misuse them, how to write a seedable generator, and a few patterns: weighted choices, a hand-written shuffle and a Monte Carlo estimate. It uses ranges, generics and protocols.

Truly random output cannot be shown on a page that must always look the same, so the first examples print only facts that are always true (a roll is between 1 and 6). The seeded examples later print exact numbers, because a seeded generator is predictable.

The everyday methods

Numeric types have a random(in:) method that accepts a range, either closed (...) or half-open (..<). Bool.random() flips a coin. Collections have randomElement(), shuffled() and shuffle().

Swift Random values from the standard library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each line prints true or a fixed value because the facts are guaranteed, whatever numbers came out. Notice the details:

  • Int.random(in: 1...6) is inclusive at both ends, while Double.random(in: 0..<1) excludes 1. With a closed range of doubles, both ends are possible.
  • randomElement() returns an optional, because an empty collection has no element. [Int]().randomElement() is nil.
  • shuffled() returns a new array, shuffle() rearranges in place and needs a var. A shuffle changes order only; the sorted result equals the original, and a shuffled deck still has 52 distinct cards.
  • A string of random letters is built by mapping over a range and picking a random character for each position.

An empty range is a crash

A random number from an empty range is impossible, so Swift traps. This is a typical bug when a range is computed from data:

Swift Random value from an empty range (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program ends with SIGILL and a backtrace, with no readable message (the build is optimized, and the check is a trap). When the range comes from user input or from a collection that might be empty, guard first, or use randomElement(), which returns nil instead of crashing.

The system generator

Every call above secretly passed using: &SystemRandomNumberGenerator(). That type is the default: it asks the operating system for random bits and is cryptographically secure and safe to call from any thread. You rarely name it, but you can ask it for raw 64-bit values:

Swift
var system = SystemRandomNumberGenerator()
let raw: UInt64 = system.next()

Use the default whenever you want unpredictable numbers: session tokens, shuffling in a real game, jitter for retries. Its weakness is exactly its strength: you cannot repeat a run, so a failing test that used it may never fail again.

Writing a seeded generator

Swift has no built-in seedable generator. Instead there is a tiny protocol, RandomNumberGenerator, with one requirement: a mutating func next() -> UInt64 that returns 64 random bits. Everything else (Int.random(in:using:), shuffled(using:), randomElement(using:), Bool.random(using:)) is built on top of it. If you provide next(), you get the whole API.

A good small choice is the SplitMix64 algorithm: a few lines, fast, and statistically fine for games, simulations and tests. It is not secure; anyone who sees a few outputs can predict the rest.

Swift A seeded generator gives repeatable results

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both generators created with seed 42 print the same list, [75, 16, 28, 35, 4], and a different seed gives a different list. Seed 42 shuffles 1 to 10 into [8, 3, 5, 6, 2, 10, 7, 4, 9, 1] every time. The last line shows the raw 64-bit values for seed 1, 10451216379200822465 and 13757245211066428519.

Three details about the code. The &+= and &* operators are the wrapping operators; this algorithm relies on overflow, and the normal + and * would trap (see numbers). The generator is a struct, and the methods are mutating, so you pass it as inout with &. And because it is a value type, copying a generator copies its position, which is both a feature and a trap:

Swift Copies replay the same numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The copy continues from the same state, so both produce identical numbers (true). That is useful for replays and "what if" simulations, and a bug when two parts of a program each hold a copy and you expected independent streams. Give each independent stream its own seed.

Why seeds matter

A seeded generator is the right tool when you need reproducibility:

  • Tests: a test that shuffles input should fail the same way twice. Print the seed when a randomized test fails, so you can replay it.
  • Simulations: scientific and financial runs must be repeatable for others to check.
  • Games: a seed can name a world (like a level code players share) or let a speedrun replay exactly.
  • Debugging: "it happened once in a thousand runs" becomes "it happens with seed 91231".

Make your functions accept a generator, as the standard library does, instead of calling the global random functions. Then production passes the system generator and tests pass a seeded one:

Swift Dice statistics with an injected generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With seed 2026 the counts are 996, 958, 1032, 1002, 1034, 978 for faces 1 to 6: close to the 1,000 each that chance predicts, but never exactly equal. The totals are always 6000 and 600. The same function runs with both generators, which is the whole point of the using: parameter.

Pitfall: modulo bias

A common beginner approach is generator.next() % 6. It looks right and is slightly wrong. If the generator produces N equally likely values and N is not a multiple of 6, some results come up more often. A tiny exhaustive example shows it: pretend the generator yields the eight values 0 to 7 with equal probability.

Swift Why next() % 6 is biased

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is [2, 2, 1, 1, 1, 1]: faces 0 and 1 are twice as likely as the others. With 64-bit values the bias is far smaller, but it exists. Int.random(in:using:) rejects the values that would cause bias, so always use it (and the other standard methods) and never reduce raw bits yourself.

Patterns

Weighted choice

Not every outcome should be equally likely. To pick an item with probability proportional to its weight, roll a number below the total and walk through the items, subtracting weights until the roll falls inside one.

Swift Weighted random choice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The three weights add up to 100, so out of 1,000 draws the counts should land near 700, 250 and 50. With seed 99 you get 682 common, 268 rare and 50 epic. Change the seed and the numbers change, but they stay close to those proportions. The dictionary keys are sorted before printing, because a dictionary has no stable order.

Shuffling by hand: Fisher-Yates

shuffled() is already correct, but writing the algorithm once is instructive, and it appears in interviews. Walk from the end of the array; swap each element with a random one at or before it.

Swift The Fisher-Yates shuffle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The result is a permutation (sorted it equals 1...10) with 10 elements, and a second run with seed 5 reproduces it exactly. Note the range 0...index is inclusive: an element may stay where it is. Using 0..<index instead is a classic mistake that produces a biased shuffle, because an element can then never remain in place.

Estimating pi with Monte Carlo

A Monte Carlo method uses many random samples to estimate something hard to compute. Throw random points into the unit square; the fraction that lands inside the quarter circle of radius 1 is about pi / 4.

Swift Estimating pi with random points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With seed 7 the estimates are 2.92 for 100 samples, 3.135 for 10,000 and 3.141 for a million. More samples usually bring the answer closer to pi, but only slowly (the error shrinks with the square root of the sample count), and a small sample can be far off. With a seed, even this experiment is repeatable.

When to use which generator

You need Use
Unpredictable values, tokens, real shuffles The default (SystemRandomNumberGenerator)
Repeatable tests, simulations, replays Your own seeded RandomNumberGenerator
Cryptographic keys A cryptography library; do not roll your own

Seeds from the clock (UInt64(Date().timeIntervalSince1970)) are a bad idea for anything secret and make runs less reproducible, not more. Pick a seed explicitly, and print it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which range gives all six faces of a die, including 6?

    1...6 is a closed range that includes 6. 1..<6 stops at 5.
  2. 2. What does [Int]().randomElement() return?

    randomElement() returns an optional so that an empty collection is not an error.
  3. 3. What must a type provide to conform to RandomNumberGenerator?

    next() returns 64 random bits; the standard library builds all random(in:using:) methods from it.
  4. 4. Two generators start from the same seed with the same algorithm. What do they produce?

    A seeded generator is deterministic. That is what makes randomized tests and simulations repeatable.
  5. 5. Why is generator.next() % 6 a poor way to roll a die?

    Unless the number of generator outputs is a multiple of 6, remainders are not equally likely. Int.random(in:using:) avoids the bias.

Summary

  • Use Int.random(in:), Double.random(in:), Bool.random(), randomElement(), shuffled() and shuffle(); closed ranges include their upper bound, half-open ranges exclude it.
  • An empty range traps, and randomElement() on an empty collection returns nil.
  • The default generator, SystemRandomNumberGenerator, is secure and not repeatable.
  • Conform a struct to RandomNumberGenerator by implementing next(); every random(in:using:), shuffled(using:) and randomElement(using:) then works with it.
  • A seeded generator gives identical sequences for identical seeds, which is ideal for tests and simulations but not secure.
  • Pass generators as inout parameters, and let functions take one so tests can inject a seeded one. Copies of a generator replay the same numbers.
  • Never reduce raw bits with %; use the standard methods to avoid modulo bias.

Next: UUID, URL and URLComponents shows how to create unique identifiers and build and parse web addresses.