Swift For Loop

Swift's for-in loop walks through ranges, arrays, dictionaries, and any other sequence, giving you a concise way to repeat code for each element.

Looping over a range

The closed range operator a...b produces a sequence from a to b inclusive, while the half-open operator a..<b stops just before b. A for-in loop over a range binds each value to a constant you name, making it the natural tool for repeating an action a fixed number of times.

for-in over a range

for number in 1...5 {
    print("Square of \(number) is \(number * number)")
}

for index in 0..<3 {
    print("Zero-based index: \(index)")
}

Looping over collections

for-in also iterates directly over arrays, sets, and dictionaries. For arrays and sets you get each element in turn; for dictionaries you get a (key, value) tuple for every entry, which you can destructure right in the loop's declaration.

for-in over arrays and dictionaries

let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
    print("I like \(fruit)")
}

let prices = ["apple": 1.2, "banana": 0.5, "cherry": 3.0]
for (name, price) in prices {
    print("\(name) costs $\(price)")
}
Note: Dictionaries are unordered in Swift, so the (key, value) pairs may print in a different order each run. Sort the keys first if you need a stable order.

Ignoring the loop variable and using stride

If you don't need the current value, replace it with an underscore to signal intent clearly. When you need a custom step size instead of the default 1, use stride(from:to:by:) or stride(from:through:by:) to generate the sequence of values.

  • Use _ in for _ in 1...3 when you only care about repeating an action a set number of times.
  • stride(from:to:by:) excludes the end value, like the half-open range operator.
  • stride(from:through:by:) includes the end value, like the closed range operator.
  • A negative stride value counts downward, e.g. stride(from: 10, through: 0, by: -2).

Custom steps with stride

for _ in 1...3 {
    print("Ping!")
}

for even in stride(from: 0, through: 10, by: 2) {
    print("Even value: \(even)")
}
Note: Inside a for-in loop, the loop variable is a constant by default; you cannot reassign it, though you may declare a new mutable variable inside the body if you need one.

for-in loop building blocks

SyntaxProducesIncludes end value?
a...bClosed rangeYes
a..<bHalf-open rangeNo
stride(from:to:by:)Custom-step sequenceNo
stride(from:through:by:)Custom-step sequenceYes

Exercise: Swift For Loop

Does Swift still support the old C-style `for i = 0; i < n; i++` loop?