Random Numbers in Swift

Here’s the translation of the Go random numbers example to Swift, formatted in Markdown suitable for Hugo:

Swift provides random number generation through its Foundation framework.

import Foundation

// For example, Int.random(in:) returns a random Int n,
// 0 <= n < 100.
print(Int.random(in: 0..<100), terminator: ",")
print(Int.random(in: 0..<100))

// Double.random(in:) returns a Double f,
// 0.0 <= f < 1.0.
print(Double.random(in: 0..<1))

// This can be used to generate random doubles in
// other ranges, for example 5.0 <= f' < 10.0.
print(Double.random(in: 5..<10), terminator: ",")
print(Double.random(in: 5..<10))

// If you want a known seed, create a new
// RandomNumberGenerator and use it for random operations.
var generator = SystemRandomNumberGenerator()
let seed: UInt64 = 42
generator.seed = seed

print(Int.random(in: 0..<100, using: &generator), terminator: ",")
print(Int.random(in: 0..<100, using: &generator))

// Creating another generator with the same seed will
// produce the same sequence of random numbers.
var generator2 = SystemRandomNumberGenerator()
generator2.seed = seed

print(Int.random(in: 0..<100, using: &generator2), terminator: ",")
print(Int.random(in: 0..<100, using: &generator2))

Some of the generated numbers may be different when you run the sample.

$ swift random-numbers.swift
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

See the Swift Standard Library documentation for references on other random quantities that Swift can provide.

In Swift, the SystemRandomNumberGenerator is used as the default random number generator. Unlike the PCG (Permuted Congruential Generator) mentioned in the original example, Swift’s SystemRandomNumberGenerator uses a cryptographically secure random number generator provided by the operating system.

The seed property of SystemRandomNumberGenerator is a Swift-specific feature that allows you to set a seed for reproducible random number sequences. This is similar to creating a new rand.Source with a known seed in the original example.

Swift’s random number generation is more integrated into the language, with methods directly on the numeric types (Int, Double, etc.) rather than using a separate rand package.