Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use for Loops in Swift
Written by Team Kodeco

A for loop in Swift is used to execute a set of statements a certain number of times. The loop iterates over a sequence of values, such as an array or a range of numbers. The basic syntax for a for loop is as follows:

for variable in sequence {
  // statements to execute
}

where variable is a variable that takes on the value of each element in the sequence, and sequence is a range of numbers or an array.

Here is an example of using a for loop to iterate over a range of numbers:

for i in 1...5 {  // range of numbers from 1 to 5
  print(i, terminator: " ")
}
// Output: 1 2 3 4 5 

Here is an example of using a for loop to iterate over an array:

let names = ["Alice", "Bob", "Charlie"]
for name in names {
  print(name, terminator: " ")
}
// Output: Alice Bob Charlie 

Here is an example of using a for loop to iterate over a dictionary:

let numbers = [1: "one", 2: "two", 3: "three"]
for (key, value) in numbers {
  print("\(key) = \(value)", terminator: " ")
}
// Output: 2 = two 1 = one 3 = three

Note: The loop variable shouldn’t be modified inside the loop, otherwise it’ll lead to unexpected behavior.

© 2024 Kodeco Inc.