Start Coding

Topics

Swift For Loops

For loops are a fundamental control flow construct in Swift, enabling efficient iteration over collections and ranges. They provide a concise way to execute a block of code repeatedly.

Basic Syntax

The basic syntax of a for loop in Swift is as follows:

for item in collection {
    // Code to be executed for each item
}

Here, item represents each element in the collection as the loop iterates.

Iterating Over Arrays

One common use of for loops is to iterate over arrays:

let fruits = ["apple", "banana", "orange"]
for fruit in fruits {
    print("I like \(fruit)")
}

This loop will print each fruit in the array.

Using Ranges

Swift for loops can also iterate over ranges:

for number in 1...5 {
    print(number)
}

This loop prints numbers from 1 to 5, inclusive.

Stride Function

For more complex iterations, use the stride(from:to:by:) function:

for i in stride(from: 0, to: 10, by: 2) {
    print(i)
}

This loop prints even numbers from 0 to 8.

Where Clause

You can add a where clause to filter iterations:

for number in 1...10 where number % 2 == 0 {
    print(number)
}

This loop only prints even numbers between 1 and 10.

Enumerating Collections

To access both the index and value of a collection, use enumerated():

let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
    print("Color \(index + 1): \(color)")
}

Important Considerations

  • For loops in Swift are more efficient than Swift While Loops when the number of iterations is known in advance.
  • Use break and continue statements to control loop execution flow.
  • When iterating over dictionaries, the order is not guaranteed.
  • For loops work seamlessly with Swift's Optionals and Type Safety features.

Related Concepts

To further enhance your Swift programming skills, explore these related topics:

By mastering for loops, you'll gain a powerful tool for efficient data processing and control flow in your Swift applications.