App 8 — 24 Apps You Can Make Today

Roll the Dice

Shake or tap to roll a die — and learn how Swift generates random numbers.

  • ios
↓ Download Playgrounds File

Every game needs dice. This app rolls one (or more) with a tap and shows the result. It's also your introduction to randomness in Swift.

What you'll build

One or more dice on screen showing their current values. Tap a button to roll — the numbers (and maybe the dice faces) update instantly.

Key concepts

Int.random(in:) — Swift makes random numbers easy. Pass a range and get back a random integer.

let roll = Int.random(in: 1...6)

@State for the current roll — Store the current die value in state so the view re-renders when it changes.

@State var dieValue = 1

Button("Roll") {
    dieValue = Int.random(in: 1...6)
}

Showing the die face — Use a switch or array to map the number to an emoji die face.

let faces = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"]

Text(faces[dieValue - 1])
    .font(.system(size: 80))

.animation() — Add a quick scale animation when the die rolls so it feels like something physical happened.

Text(faces[dieValue - 1])
    .animation(.spring(response: 0.3), value: dieValue)

Randomness and state

Every time you call Int.random(in:), you get a different number. Assigning it to @State triggers a view update. That two-line combination is the core of a huge number of games and simulations.

Download and run it

Open the Playgrounds file from GitHub, hit Run, and roll.

← All apps in this book