Learn/Swift/4. Making decisions
Lesson 4 of 8
Sign in

Swift, lesson 4

Making decisions

So far every program has run the same lines every time. Real programs react to their input: a game checks whether you won, a shop checks whether you get free shipping. That takes conditions.

Comparisons and Bool

A comparison produces a Bool, either true or false:

OperatorMeaning
==equal to
!=not equal to
< >

2 exercises to try what you just read.

Exercise 1

Cinema tickets

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

less than, greater than
<= >=at most, at least

Note the double == for "equal". A single = assigns a value, and Swift refuses to compile if total = 10 because assignment does not produce a Bool. That small rule catches a classic bug.

if, else if, else

Swift checks each condition from the top and runs the first block whose condition is true, then skips the rest. The braces are always required, even for a single line, and the condition does not need parentheses. The condition must be a real Bool: if count { ... } with an Int is a compile error, so you write if count > 0.

Combining conditions

  • a && b is true only when both are true ("and").
  • a || b is true when at least one is true ("or").
  • !a flips a Bool ("not").

Swift stops evaluating as soon as it knows the answer. If the left side of && is false, the right side is never checked. Use parentheses whenever mixing && and ||; they make the intent obvious to readers.

if as a value

An if can also produce a value directly, as long as every branch gives the same type:

For a quick two-way choice you can also use the ternary operator condition ? valueIfTrue : valueIfFalse, but keep it to short, simple cases.

switch

When you compare one value against many possibilities, switch is tidier than a long chain of else if. Each case can list single values, several values, or a range:

Three rules make Swift's switch safer than in many languages:

  1. It must be exhaustive: every possible value has to be covered, which usually means ending with default.
  2. There is no fall-through. Once a case runs, the switch is finished; you never write break at the end of a case.
  3. Every case needs at least one statement. Write break if a case should do nothing.

Ranges come in two shapes: a...b includes both ends, and a..<b stops just before b.

Further reading

  • Control Flow: conditional statements
  • Basic Operators: comparison, logical and range operators

Read a visitor's age and print their ticket type and price. Use a switch with ranges.

AgeOutput
0 to 4Free
5 to 17Child: $8
18 to 64Adult: $15
65 and upSenior: $10

Input: one line with a whole number, the age (0 or more).

Output: one line from the table.

Sample input:

Sample output:

A year is a leap year if it is divisible by 4, except years divisible by 100 are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 and 2026 are not.

Input: one line with a year (a positive whole number).

Output: Leap year or Common year.

Sample input:

Sample output:

Try writing the whole rule as one condition using %, && and ||.

let temperature = 31

if temperature > 30 {
    print("Hot! Drink water.")
} else if temperature < 5 {
    print("Cold. Grab a coat.")
} else {
    print("Nice weather.")
}
let age = 15
let withAdult = true
if age >= 13 && (age < 16 || withAdult) {
    print("You can watch the film.")
}
let label = if temperature > 25 { "warm" } else { "cool" }
let hour = 14
switch hour {
case 0..<12:
    print("Good morning")
case 12, 13:
    print("Lunch time")
case 14...17:
    print("Good afternoon")
default:
    print("Good evening")
}
12
Child: $8
2024
Leap year