Loop

Swift Arrays: Loop

Use for-in to loop values.

Use enumerated() for index and value.


Loop Elements

Loop values with for-in, or use enumerated() for index and value.

Example

let fruits = ["Apple", "Banana", "Cherry"]
for fruit in fruits {
  print(fruit)
}
for (i, fruit) in fruits.enumerated() {
  print("\(i): \(fruit)")
}

Get index and value with enumerated().



forEach

Use forEach for a functional style loop. It reads values but cannot use break/continue.

Example

let fruits = ["Apple", "Banana", "Cherry"]
fruits.forEach { print($0) }
fruits.enumerated().forEach { print("\($0.offset): \($0.element)") }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *