Swiftly

Swift 5.7 references for busy coders

For-in

The common for loop syntax for (i = a; i < b; i++) does not exist in Swift. Instead, for-in can be modified to have an index using tuples and enumerated:

Simple for-in

let birds = ["Owl", "Crane"]
for bird in birds {
  print(bird)
}
// Output:
// Owl
// Crane

For-in with index

let birds = ["Owl", "Crane"]
for (i, bird) in birds.enumerated() {
  print("[\(i)]: \(bird)")
}
// Output:
// [0]: Owl
// [1]: Crane

For-in-where

struct Player { let name: String, level: Int }

let players = [
  Player(name: "Rashida", level: 1),
  Player(name: "Tomoko", level: 1),
  Player(name: "Isabella", level: 20)
]

for player in players where player.level == 1 {
  print("\(player.name) is a beginner.")
}

// Output:
// Rashida is a beginner.
// Tomoko is a beginner.

Traditional for loop

It is still possible to create a for loop similar to for (i = a; i < b; i++):

let birds = ["Owl", "Crane"]
for i in 0 ..< birds.count {
  print("[\(i)]: \(birds[i])")
}
// Output:
// [0]: Owl
// [1]: Crane

See also

Further reading