Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow
for i in 1...5 {
    print(i)
}

for i in 1..<5 {       // half-open range — 1 to 4
    print(i)
}

for (i, item) in ["a", "b", "c"].enumerated() {
    print("\(i): \(item)")
}

var n = 16
while n > 1 {
    n /= 2
}

repeat {
    n -= 1
} while n > 0

... is closed (inclusive). ..< is half-open (excludes upper). repeat-while is Swift's name for do-while.

Functional iteration via map, filter, reduce:

[1, 2, 3, 4, 5].map { $0 * 2 }     // [2, 4, 6, 8, 10]
[1, 2, 3, 4, 5].filter { $0 > 2 }   // [3, 4, 5]
[1, 2, 3, 4, 5].reduce(0, +)        // 15

$0 is the implicit name for the first lambda parameter. + works as a function reference.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…