Swift Tutorial · Swift Basics · Lesson 8 of 30
Swift Loops and Ranges
Loop with for-in over ranges and collections, stride, while and repeat-while, and labelled statements.
for-in and ranges
1...5 includes 5, 1..<5 excludes it. stride(from:to:by:) steps by any amount, enumerated() gives
index and value, and where filters inside the loop header.
for i in 1...3 { print(i, terminator: " ") }
print()
for i in stride(from: 10, through: 0, by: -5) { print(i, terminator: " ") }
print()
let fruits = ["apple", "banana", "cherry"]
for (index, fruit) in fruits.enumerated() { print("\(index): \(fruit)") }
for n in 1...10 where n % 4 == 0 { print("multiple of 4: \(n)") }
Output
1 2 3 10 5 0 0: apple 1: banana 2: cherry multiple of 4: 4 multiple of 4: 8
Run this on your computer — see “Get Started” for setup.
while and repeat-while
repeat { } while condition runs the body at least once. Labels let break and continue target an outer loop.
var stock = 3
while stock > 0 {
print("Selling one, \(stock) left before sale")
stock -= 1
}
var attempts = 0
repeat {
attempts += 1
} while attempts < 3
print("attempts: \(attempts)")
outer: for row in 1...3 {
for col in 1...3 {
if col == 2 { continue }
if row == 3 { break outer }
print("(\(row),\(col))", terminator: " ")
}
}
print()
Output
Selling one, 3 left before sale Selling one, 2 left before sale Selling one, 1 left before sale attempts: 3 (1,1) (1,3) (2,1) (2,3)
Run this on your computer — see “Get Started” for setup.
Test yourself
Which loop always runs its body at least once?
whilefor-inrepeat-whilestride
Show answer
Answer: repeat-while