Mastering Loops in Swift: A Comprehensive Guide

Understanding Loops

In Swift, loops are an essential concept that allows you to repeat a set of actions until a certain condition is met. In simple terms, a loop is a sequence of instructions that runs repeatedly until it reaches a stopping point. There are different types of loops in Swift, including for-in, forEach, while, and repeat-while loops.

The Syntax of For-In Loops

A for-in loop starts with the keyword “for,” followed by a constant element, the “in” keyword, and finally, the sequence you want to loop over.

for element in sequence {
    // code to be executed
}

Let’s consider an example where we have a list of stocks, each with its price and date. We can use a for-in loop to iterate over the array and print the data for each stock.

let stocks = [
    (price: 100.0, date: "2022-01-01"),
    (price: 120.0, date: "2022-01-15"),
    (price: 110.0, date: "2022-02-01")
]

for stock in stocks {
    print("Price: \(stock.price), Date: \(stock.date)")
}

In Swift, an array is an ordered collection of values of the same type. We can use for-in loops to iterate over the stored values and access each value in the array.

let locations = ["New York", "London", "Paris", "Tokyo"]
for location in locations {
    print("Jogging speed at \(location): 10 km/h")
}

Using the Where Clause

Sometimes, we want to restrict the sequence to elements that match a particular condition. In such cases, we can use the “where” keyword.

let goals = [
    (title: "Learn Swift", completed: true),
    (title: "Run a marathon", completed: false),
    (title: "Read a book", completed: true)
]

for goal in goals where goal.completed {
    print("Completed goal: \(goal.title)")
}

Enumerated() and Indices

To access each index of the element simultaneously, we can use the “enumerated()” instance method. This returns a sequence of pairs containing the index and the value of the element. Alternatively, we can use “indices” to access the index of the element in the array.

let locations = ["New York", "London", "Paris", "Tokyo"]
for (index, location) in locations.enumerated() {
    print("Location at index \(index): \(location)")
}

Range and Stride

For-in loops can also be used to iterate over hardcoded numeric ranges. We can divide ranges into two parts: closed ranges (using the… operator) and half-open ranges (using the..< operator).

for i in 1...10 {
    print("Number: \(i)")
}

Dictionaries and KeyValuePairs

We can iterate over dictionaries using for-in loops, although the result will be unordered. We can also use “KeyValuePairs” to achieve ordered key-value pairs, sacrificing fast look-up time for linear time.

let dict = ["name": "John", "age": 30]
for (key, value) in dict {
    print("Key: \(key), Value: \(value)")
}

Enums: Iterating Over Cases

Finally, we can iterate over enums in Swift by conforming to the “CaseIterable” protocol. This provides a collection of all enum values, which we can access using the “allCases” property.

enum Color: CaseIterable {
    case red, green, blue
}

for color in Color.allCases {
    print("Color: \(color)")
}

Leave a Reply