Operators
Prerequisites: Booleans and comparisons
An operator is a symbol that works on values, like + or &&.
Arithmetic and assignment
+, -, *, /, %, plus compound assignment:
var score = 10
score += 5
score -= 2
score *= 2
print(score)
26
Swift has no ++ or -- operators — write score += 1.
Logical operators
let age = 20
let hasTicket = true
print(age >= 18 && hasTicket)
print(age < 13 || age > 65)
print(!hasTicket)
true
false
false
&&(and) — true only if both sides are true.||(or) — true if either side is true.!(not) — flipstrueandfalse.
Swift stops evaluating as soon as the answer is known: in a && b, if
a is false, b is never checked.
The ternary operator
condition ? valueIfTrue : valueIfFalse picks one of two values:
let temperature = 30
let advice = temperature > 25 ? "Wear a hat" : "Bring a jacket"
print(advice)
Wear a hat
Range operators
1...5— a closed range: 1, 2, 3, 4, 5.1..<5— a half-open range: 1, 2, 3, 4 (excludes 5).
Ranges are used with loops and switch, covered in their own lessons.
Common mistakes
- Writing
=(assignment) in a condition instead of==. Swift refuses to compileif x = 5, which prevents a classic bug.
Practice
A shop gives free delivery if an order is over 50 or the customer is a
member. With total = 42 and isMember = true, print whether delivery
is free, using the ternary operator to print Free delivery or
Delivery: $5.
Show solution
let total = 42
let isMember = true
print(total > 50 || isMember ? "Free delivery" : "Delivery: $5")
Free delivery