Control Flow
if / elif / else
Section titled “if / elif / else”Conditions are always wrapped in parentheses. Bodies use braces.
let score = 85
if (score >= 90) { print("A")} elif (score >= 80) { print("B")} elif (score >= 70) { print("C")} else { print("F")}Match a value against multiple cases. Cases are tested top-to-bottom; first match wins. Use _ for the default case.
let cmd = "stop"
match (cmd) { "start" { print("starting") } "stop" { print("stopping") } "restart" { print("restarting") } _ { print("unknown command") }}Cases can be any expression (compared with ==):
let x = 10
match (x) { 5 * 2 { print("ten") } 5 * 3 { print("fifteen") } _ { print("other") }}// tenType patterns with is
Section titled “Type patterns with is”Use is to match by type name or class:
match (value) { is "int" { print("integer") } is "string" { print("string") } is "array" { print("array") } is MyClass { print("a MyClass instance") } _ { print("something else") }}Guard clauses with when
Section titled “Guard clauses with when”Use when for conditional matching:
let score = 85
match (score) { when score >= 90 { print("A") } when score >= 80 { print("B") } when score >= 70 { print("C") } _ { print("F") }}// BMixing patterns
Section titled “Mixing patterns”Equality, type, and guard patterns can be freely mixed:
let x = -5
match (x) { 0 { print("zero") } when x > 0 { print("positive") } when x < 0 { print("negative") }}If no case matches and there is no default, nothing happens.
let i = 0while (i < 5) { print(i) i++}for (range)
Section titled “for (range)”for (var in start..end) — end is exclusive.
for (i in 0..5) { print(i) // 0, 1, 2, 3, 4}
let n = 10for (i in 1..n + 1) { print(i) // 1 through 10}for-in (arrays)
Section titled “for-in (arrays)”let names = ["alice", "bob", "charlie"]for (name in names) { print("hello %{name}")}for-in (maps)
Section titled “for-in (maps)”Iterating a map yields {key, value} entries. You can destructure directly:
let config = {host: "localhost", port: 8080}
// Destructuring (preferred)for ({key, value} in config) { print("%{key}: %{value}")}
// Without destructuringfor (entry in config) { print("%{entry.key}: %{entry.value}")}break and continue
Section titled “break and continue”break exits the innermost loop. continue skips to the next iteration. Both work in while, for, and for-in.
// Skip odd numbersfor (i in 0..10) { if (i % 2 != 0) { continue } print(i) // 0, 2, 4, 6, 8}
// Stop at first matchlet names = ["alice", "bob", "charlie"]for (name in names) { if (name == "bob") { break } print(name) // alice}
// break in whilelet n = 0while (true) { if (n >= 3) { break } print(n) // 0, 1, 2 n++}In nested loops, break and continue only affect the innermost loop.