if / else if / else
Parentheses around the condition are not required. Braces { } are mandatory.
if temperature > 80 {
print("Overheating")
} else {
print("Normal temperature")
}
else if chains are fully supported and may be nested to any depth:
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else if score >= 70 {
print("C")
} else {
print("F")
}
while
Repeats the body as long as the condition is truthy.
let retries = 0
while retries < 5 {
print("Attempting connection...")
retries += 1
}
for / in
Iterates over every element of a List. The loop variable is scoped to the loop body.
let nodes = ["web-01", "web-02", "db-01"]
for node in nodes {
print("Checking node: " + node)
}
Combined with range() for numeric iteration:
for i in range(5) {
print("Step " + str(i)) // 0 1 2 3 4
}
for i in range(1, 6) {
print(str(i)) // 1 2 3 4 5
}
break
Immediately exits the nearest enclosing while or for loop.
let i = 0
while i < 100 {
i += 1
if i > 10 {
break // stops the loop when i reaches 11
}
}
print(i) // 11
Use break inside a loop. The current interpreter does not consistently reject it outside loops; that behavior should not be relied on.
continue
Skips the rest of the current loop iteration and jumps to the next one.
for i in range(10) {
if i % 2 == 0 {
continue // skip even numbers
}
print(i) // prints 1, 3, 5, 7, 9
}
Use continue inside a loop. The current interpreter does not consistently reject it outside loops; that behavior should not be relied on.