← Swift tutorial

Swift

Loops

Swift's for-in loop steps through a range or collection directly.

Example: two ranges, one small but important difference

var total = 0
for i in 1...5 {
    total += i
}
print("Total: \(total)")
Total: 15

1...5 (three dots) includes both endpoints, 1 through 5. 1..<5 (two dots and a less-than) excludes the last one, covering 1 through 4 only — a genuinely easy pair to mix up, and worth double-checking whenever an off-by-one result shows up unexpectedly in your own code.

Example
var total = 0
for i in 1...5 {
    total += i
}
print("Total: \(total)")
Output
Total: 15