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.
Some of the generated numbers may be different when you run the sample.
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.