Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 53 / 68

Generating random numbers

This lesson covers generating random numbers with arc4random_uniform in Objective-C, with the aim of building things with a random element such as dice or rock-paper-scissors.

arc4random_uniform() generates a random number. Use it for dice, lotteries, and the like — the result changes on every run.

The sample code picks a dice roll from 1 to 6 with arc4random_uniform(6) + 1 and one of Rock, Scissors, or Paper from an array with choices[arc4random_uniform((uint32_t)choices.count)].

A common early stumble is the difference from C's standard rand(). arc4random_uniform() needs no initialisation such as srand() and produces better-distributed values with less fuss.

In professional work, this is indispensable wherever you want an unpredictable element — item drops in a game, sampling in a simulation.

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

๐Ÿงช This site can't compile or run Objective-C 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)