Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 146 ยท Control Flow

Loops

Learn Swift loops - for-in over ranges and collections, stride, while, repeat-while, enumerated(), zip, where clauses and the pitfalls that crash programs.

A loop repeats a block of code. Swift gives you three loop statements, and one of them, for-in, does almost all the work. There is no C-style for (int i = 0; i < n; i++) in Swift. That is a deliberate choice: most loops in real programs mean "do this for every element" or "do this for every number in a range", and for-in says exactly that, with no index variable to get wrong and no off-by-one error at the end.

This lesson covers for-in over ranges, arrays, dictionaries and strings, counting with stride, the conditional loops while and repeat-while, and the helpers enumerated(), zip and reversed() that replace most hand-written index arithmetic. Jumping out of a loop early is the topic of the next lesson, break, continue and Labels.

for-in over a range

A range such as 1...5 is a value you can loop over. The loop constant (n here) is created fresh on every pass and is a let, so you cannot modify it.

Swift Counting with ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

1...5 is a closed range (both ends included) and 0..<3 is a half-open range (the upper bound is excluded). Half-open ranges fit counting from zero: 0..<array.count visits every valid index and nothing more. The Ranges lesson explains the types behind them.

If you do not need the loop variable, write an underscore. This tells the reader (and the compiler) that you are only repeating something a fixed number of times.

Swift
for _ in 1...3 {
    print("hip hip hooray")
}

A range must go upward. 5...1 is not an empty range, it is a runtime trap: the program stops because a range requires lowerBound <= upperBound (our optimized runner shows an illegal-instruction signal and a backtrace; a debug build prints a fatal error). When the bounds come from variables or user input, check them first, or use stride or reversed() as shown below.

for-in over collections

Any sequence works: arrays, sets, dictionaries, strings, ranges and many more. Looping over an array gives you its elements in order.

Swift Arrays, strings and dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A String is a sequence of Character values, so the second loop prints one letter at a time. A dictionary yields (key, value) tuples, which you can unpack right in the loop header with (item, count). The dictionary's own order is random from one run of the program to the next (Swift randomizes it on purpose), so the example sorts first. If you print an unsorted dictionary loop, never rely on the order.

Filtering with where

A where clause skips the elements that do not match, without an if inside the body:

Swift
for n in 1...20 where n.isMultiple(of: 5) {
    print(n)    // 5, 10, 15, 20
}

This reads well when the filter is one short condition. For longer logic, an if or a call to filter is clearer. The higher-order functions lesson covers filter, map and reduce.

Pattern in the loop header

The loop variable can be any pattern, not only a name. for case let lets you pick out some elements, for example only the non-nil values of an array of optionals:

Swift Looping over optionals with for case

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The number? pattern matches only .some values and binds the content to number. The Pattern Matching lesson builds on this.

Index and element together: enumerated()

Sometimes you need the position as well as the value. Do not loop over indices and subscript; ask the sequence for enumerated(), which yields (offset, element) pairs:

Swift enumerated and zip

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that the offset starts at 0 and is not a valid array index for slices or other collections whose indices do not start at zero. It is the count of elements seen so far. zip(a, b) walks two sequences in lockstep and stops when the shorter one ends, so no out-of-range access is possible. The one-sided range 1... counts forever, which is safe here because zip stops at the end of "abc".

Counting with steps: stride

For steps other than 1, or for counting down, use stride. There are two forms: stride(from:to:by:) excludes the end value, and stride(from:through:by:) includes it.

Swift stride and reversed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

stride works with any Strideable type, including Double (on our Linux runner, a program that strides over Doubles needs import Foundation to link the math library, which is why the example imports it). Be careful with floating-point steps: values like 0.1 cannot be represented exactly, so a loop stride(from: 0, through: 1, by: 0.1) may give a last value slightly different from what you expect. Prefer an integer loop and divide.

To count down through a range, call reversed(). It is lazy and does not copy anything.

while

while evaluates its condition before each pass. If the condition is false at the start, the body never runs. Use it when you do not know the number of passes in advance.

Swift A while loop: the Collatz sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Starting at 27, the sequence takes 111 steps to reach 1. No one has proven that every starting number does, which is a nice reminder that while loops can in theory run forever. Always make sure something in the body moves the condition toward false.

A common Swift idiom pairs while with an optional binding: while let repeats as long as an expression returns a non-nil value.

Swift while let

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

popLast() returns nil when the array is empty, which ends the loop. The same pattern drives iterators, line-by-line input (while let line = readLine()) and many parsing loops. See Optionals for the binding syntax.

repeat-while

repeat-while checks the condition after each pass, so the body always runs at least once. It is the right choice when you must do something first and then decide whether to continue: ask for input, roll a die, retry an operation.

Swift repeat-while runs at least once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

If you wrote this as a plain while delay < 10, you would need to prepare the state differently to get the first attempt. repeat-while is used less often than while, but when the "do it once first" logic fits, it is the cleanest option.

Modifying a collection while you loop

A for-in loop works on a copy of the sequence it started with (arrays are value types, see Collections Overview). Changing the array inside the loop does not change what the loop sees, and Swift does not allow you to mutate the loop constant either.

Swift Removing items safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

removeAll(where:) is both shorter and safer than a hand-written loop with remove(at:), which shifts later elements and invalidates your indices. To update elements in place, loop over indices, not over 0..<count, and subscript into the array.

Choosing the right loop

  • for-in is the default. Use it for every element of a sequence or a known range.
  • stride when the step is not 1 or when you count down.
  • while when the number of passes depends on a changing condition.
  • repeat-while when the body must run at least once.
  • forEach is a method, not a statement: break, continue and return behave differently inside it (a return only leaves the closure). Prefer for-in unless you are chaining calls.

For very large ranges, loops are fast: with optimization enabled, simple for-in loops over integer ranges compile to the same machine code as a C loop. You do not need while and manual counters for speed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does for i in 0..<3 visit?

    A half-open range excludes its upper bound, so the loop sees 0, 1 and 2.
  2. 2. Which loop always runs its body at least once?

    repeat-while checks its condition after the body, so the body runs first no matter what.
  3. 3. What happens when you execute for n in 5...1 { }?

    A closed range requires lowerBound <= upperBound. Use stride(from:through:by:) or (1...5).reversed() to count down.
  4. 4. Which call prints 0, 5, 10 (and not 15)?

    through: includes its end value and to: excludes it, so both calls give 0, 5, 10. There is no by method on ranges.
  5. 5. What does enumerated() give you for each element?

    enumerated() yields (offset, element) pairs. The offset counts from zero and is not necessarily a valid index of the collection.

Summary

  • for-in is Swift's main loop. It works on ranges, arrays, sets, dictionaries, strings and any other sequence.
  • 1...5 includes the end, 0..<5 excludes it, and an upside-down range traps at run time.
  • Use _ when you do not need the loop variable, where to filter, and for case to match patterns.
  • enumerated() gives offsets, zip walks two sequences together, and reversed() counts down.
  • stride(from:to:by:) and stride(from:through:by:) handle other step sizes; avoid fractional steps when exact values matter.
  • while tests before each pass, repeat-while tests after, and while let runs as long as an optional has a value.
  • To remove or change elements, use removeAll(where:) or loop over indices instead of editing while iterating.

Next: break, continue and Labels