Swift For Loop

Swift For Loop

Use for-in to iterate over ranges, arrays, dictionaries, and other sequences.


Iterate a Range

Use a range to loop a fixed number of times.

Example

for i in 1...3 {
  print(i)
}

This example iterates from 1 to 3 inclusive.



Iterate an Array

Loop through an array with for-in or enumerated() to access index and value.

Example

let nums = [10, 20, 30]
for n in nums {
  print(n)
}
for (index, value) in nums.enumerated() {
  print("index: \(index), value: \(value)")
}

Use enumerated() to get index and value together.

Comments

Leave a Reply

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