Swiftly

Swift 5.1 references for busy coders

For-in

The common for loop for (i = a; i < b; i++) does not exist in Swift. Instead, the 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
  let 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 novice.
// Tomoko is a novice.

See also