Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. for-in / while / repeat-while

for-in / while / repeat-while

Swift provides three types of loops: for-in for iterating over a collection in order, while for repeating while a condition is true, and repeat-while for executing at least once before checking the condition.

Syntax

// for-in (iterate over a collection)
for variable in collection {
    // body
}

// stride (iterate over a numeric range)
for variable in stride(from: start, to: end, by: step) {
    // body
}

// while (repeat while condition is true)
while condition {
    // body
}

// repeat-while (execute at least once)
repeat {
    // body
} while condition

Syntax Overview

SyntaxDescription
for i in 0..<5Iterates from 0 to 4 (half-open range, end not included).
for i in 0...4Iterates from 0 to 4 (closed range, end included).
for _ in rangeUses _ to ignore the loop variable when it is not needed.
stride(from:to:by:)Iterates with a specified step size. A negative step value iterates in reverse.
stride(from:through:by:)Iterates with a specified step size, including the end value.
for (index, value) in array.enumerated()Retrieves both the index and value on each iteration.

Sample Code

// Iterate over an array
let fruits = ["Apple", "Orange", "Grape"]
for fruit in fruits {
    print(fruit)
}

// Retrieve index and value together
for (i, fruit) in fruits.enumerated() {
    print("\(i + 1): \(fruit)")
}

// Count up by 2 using stride
for n in stride(from: 0, to: 10, by: 2) {
    print(n, terminator: " ") // 0 2 4 6 8
}
print()

// while loop
var count = 3
while count > 0 {
    print("Count: \(count)")
    count -= 1
}

// repeat-while (runs at least once regardless of the condition)
var num = 0
repeat {
    print("repeat: \(num)")
    num += 1
} while num < 3

Notes

Swift does not have a C-style for (var i = 0; i < n; i++) loop. To iterate over a numeric range, use the range operator (0..<n) or stride().

Use break to exit a loop early, and continue to skip to the next iteration. See break / continue / return for details.

If you find any errors or copyright issues, please .