iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

for-in / while

Swift loops are for-in over any Sequence, while, and repeat … while. Combine with Swift’s sequence operators and the imperative loop almost disappears from real code.

for-in + while + sequence ops

EXAMPLE
// 1) for-in — works on any Sequence
for n in 1...5 { print(n) }           // 1, 2, 3, 4, 5 inclusive
for n in 1..<5 { print(n) }           // 1, 2, 3, 4 exclusive
for n in stride(from: 0, to: 10, by: 2) { print(n) }   // 0, 2, 4, 6, 8
for c in "hello" { print(c) }
for (i, c) in "hello".enumerated() { print(i, c) }
for (key, value) in ["Ada": 36, "Bo": 28] { print(key, value) }

// 2) while
var n = 0
while n < 5 { n += 1 }

repeat {
    n -= 1
} while n > 0

// 3) where clause — filter inside the loop header
for n in 1...10 where n.isMultiple(of: 3) {
    print(n)
}

// 4) break + continue
for n in 1...10 {
    if n == 7 { break }
    if n % 2 == 0 { continue }
    print(n)
}

// 5) Labels — break / continue outer loops
outer: for i in 1...5 {
    for j in 1...5 {
        if j > i { continue outer }
        if i * j > 10 { break outer }
    }
}

// 6) Functional alternatives — often shorter than for
let nums = [1, 2, 3, 4, 5]
let doubled = nums.map { \$0 * 2 }
let evens   = nums.filter { \$0.isMultiple(of: 2) }
let sum     = nums.reduce(0, +)
let pairs   = zip(nums, nums.dropFirst()).map { (\$0, \$1) }

Why it matters

for … where filters in-place without a guarded body. Most idiomatic Swift uses sequence operators (map, filter, reduce) over for-loops — shorter and more obvious.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
for i in 0..<5 { print(i) }
for item in ["a","b","c"] { print(item) }

var n = 3
while n > 0 { print(n); n -= 1 }
Try it Yourself »

Discussion

Loading…