Ad space (banner)
๐ŸฆSwift Lessons
Lesson 53 / 68

Generating Random Numbers

In this lesson you will learn how to generate random numbers with random(in:) in Swift, so you can build things with an element of chance such as dice or rock-paper-scissors. This is for anyone searching for "Swift random number generation".

Int.random(in:) and an array's randomElement() give you a random number, or a randomly chosen value from an array. Use them for dice rolls and raffles. The result changes every time you run it.

The sample code rolls a die from 1 to 6 with Int.random(in: 1...6) and picks one of Rock, Scissors, and Paper with choices.randomElement()!.

A common stumbling block for beginners is that randomElement() returns an Optional, because the array might be empty. You either force-unwrap with ! as the sample does, or handle it more safely with if let.

In real-world development random values are essential wherever you want an unpredictable element, from shuffling in a game to sampling in a simulation, and a fixed seed reproduces the same sequence for tests.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)