In Swift, collections are a fundamental concept that allows us to store and manage groups of related data in a structured way. This article will focus on how to iterate over these collections and modify them.
Arrays are ordered collections of values. To loop over an array in Swift, we use the for-in
loop. Here's an example:
let numbers = [1, 2, 3, 4, 5] for number in numbers { print(number) }
In this example, number
is a constant that takes on each value in the array numbers
one by one, and then prints it.
If you need to know the index of each item as well as its value, you can use the enumerated()
method to iterate over the array:
for (index, number) in numbers.enumerated() { print("Item \(index): \(number)") }
Sets are unordered collections of unique values. Like arrays, we can use a for-in
loop to iterate over a set:
let colors = Set(["red", "green", "blue"]) for color in colors { print(color) }
Since sets are unordered, the order in which the items are printed is not guaranteed.
Dictionaries are collections of key-value pairs. When we loop over a dictionary, we get access to each key-value pair as a tuple. Here's an example:
let capitals = ["France": "Paris", "Spain": "Madrid", "UK": "London"] for (country, capital) in capitals { print("\(capital) is the capital of \(country)") }
In Swift, you cannot directly modify a collection while iterating over it. This is because it could lead to unexpected behavior or runtime errors.
However, if you need to modify a collection based on its own elements, you can create a copy of the collection and modify that instead. Here's an example:
var numbers = [1, 2, 3, 4, 5] var squaredNumbers = [Int]() for number in numbers { squaredNumbers.append(number * number) } numbers = squaredNumbers
In this example, we create a new array squaredNumbers
, square each number in the original numbers
array, and append it to squaredNumbers
. Then we replace the original numbers
array with squaredNumbers
.
By the end of this unit, you should have a solid understanding of how to loop over and modify collections in Swift. Practice these concepts with different types of collections and operations to reinforce your learning.