Coding for All
Lesson 25: Roll a Six
Roll a Six Grand finale: keep rolling a dice until you get a 6.
1func rollDice() -> Int {
2 return Int.random(in: 1...6)
3}
4
5var roll = rollDice()
6while roll != 6 {
7 print(roll)
8 roll = rollDice()
9}
10print("You rolled a 6!")
Terminal
$ swift main.swift
(prints a random number, different every run)
Every line, explained
func rollDice() -> Int {
func defines a function: your own named block of code. Defining it does nothing on its own; it waits until somebody calls it. In a Swift script, define a function before the line that calls it. This one promises to hand back an Int: a dice roll.
return Int.random(in: 1...6)
Int.random(in: 1...6) hands back a random whole number from the range 1...6, a built-in dice roll! Notice the range syntax and the argument label in:, both very Swift.
}
This } closes the function.
var roll = rollDice()
Calls rollDice and stores the number it returns: our first roll. It will change, so it gets var.
while roll != 6 {
A while loop repeats its block for as long as the condition is true. The condition is checked again before every trip around the loop. != means "not equal": keep looping while the roll is NOT a 6.
print(roll)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Shows each roll that wasn't a 6.
roll = rollDice()
Rolls again, replacing the old number. Then the loop checks the condition again.
}
This } closes the while loop.
print("You rolled a 6!")
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. Runs once, the moment a 6 finally appears. You just used let and var, a function with a return value, ranges, a loop and randomness. Real Swift!