Control Flow
Shape is expression-oriented.
If Expressions
Section titled “If Expressions”let score = 84
let grade = if score >= 90 { "A"} else if score >= 80 { "B"} else { "C"}
print(grade)Blocks Return Values
Section titled “Blocks Return Values”The last expression in a block is the value.
let value = { let base = 10 base * 2}
print(value) // 20A trailing semicolon discards the value and yields ().
let unit = { 1;}For Loops
Section titled “For Loops”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})")}While Loops
Section titled “While Loops”let i = 0
while i < 3 { print(i) i = i + 1}Break and Continue
Section titled “Break and Continue”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 = 0loop { if i >= 5 { break } print(i) i = i + 1}Break with Value
Section titled “Break with Value”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 > 10This 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.