Skip to main content

Control Flow

if / else

Use if to execute a block conditionally. The condition must be a Bool expression — there is no implicit conversion from other types.

var score = 60

if score > 50 {
print("Passed")
} else {
print("Failed")
}

Chain additional conditions with elseif:

var score = 80

if score >= 90 {
print("A")
} elseif score >= 75 {
print("B")
} else {
print("C")
}
caution

Conditions such as if score { … } are a compile error. Always compare explicitly, e.g. if score != 0 { … }.

for-in

Use for-in to iterate over the elements of a collection.

var fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
print(fruit)
}

for-in can also iterate over a Range:

for i in Range(5) {
print("\{i}") // 0, 1, 2, 3, 4
}

while

Use while to repeat a block as long as a condition is true. The condition is evaluated before each iteration.

var i = 0
while i < 3 {
print("\{i}")
i = i + 1
}
// Prints 0, 1, 2

break

Use break to exit a loop immediately.

var values = [3, 7, 2, 9, 4]
for v in values {
if v > 8 {
break
}
print("\{v}") // Prints 3, 7, 2
}

break works in both for-in and while loops.

do

Use do to create an explicit scope block. Variables declared inside are not visible outside.

var x = 1

do {
var x = 2
print("\{x}") // Prints 2
}

print("\{x}") // Prints 1

Ternary Conditional Expression

The ternary ?: expression produces one of two values based on a condition. Unlike if, it is an expression and can appear anywhere a value is expected.

var passed = true
var message = passed ? "Congratulations!" : "Try again."

See Operators for the full syntax.