Skip to content

Control Flow

Shape is expression-oriented.

let score = 84
let grade = if score >= 90 {
"A"
} else if score >= 80 {
"B"
} else {
"C"
}
print(grade)

The last expression in a block is the value.

let value = {
let base = 10
base * 2
}
print(value) // 20

A trailing semicolon discards the value and yields ().

let unit = {
1;
}
for i in 0..5 {
print(i)
}

Destructuring works in loop bindings:

let points = [{x: 1, y: 2}, {x: 3, y: 4}]
for {x, y} in points {
print(f"({x}, {y})")
}
let i = 0
while i < 3 {
print(i)
i = i + 1
}
for i in 0..10 {
if i == 2 {
continue
}
if i == 6 {
break
}
print(i)
}

loop creates an infinite loop. Use break to exit:

var i = 0
loop {
if i >= 5 {
break
}
print(i)
i = i + 1
}

break can carry a value, making loop an expression. The value passed to break becomes the result of the loop block:

let result = loop {
let x = compute()
if x > 10 {
break x * 2
}
}
// result is the first x * 2 where x > 10

This pattern is useful when a value must be computed iteratively and the number of iterations is not known in advance.

match is also an expression. See Pattern Matching.