← Back to archive

Development · Swift

Swift loops: for-in, while, and repeat-while

Choose a loop based on the data to traverse and when its stopping condition should be checked.

Read the Korean original on Velog ↗English translation

Development archive cover

Loops repeat work. The right form depends on whether there is a collection to traverse and whether the condition should be checked before or after each iteration.

Traversing collections with for-in

let numbers = [2, 4, 6]
for number in numbers {
    print(number)
}

let words = ["elephant": "코끼리", "lion": "사자"]
for (english, korean) in words {
    print("\(english): \(korean)")
}

A dictionary element is a key–value tuple. Do not rely on a particular dictionary iteration order.

Conditional loops with while

var count = 0
while count < 3 {
    count += 1
}

repeat {
    count -= 1
} while count > 0

while checks its condition first, so the body may never run. repeat-while checks afterward, so the body runs at least once. Use for-in for a sequence of values and a while loop when a condition controls repetition.

← Back to archive