5.1. For loops
For loops are the most common loops in Swift, and you'll probably use this loop for more than 90% of cases. We use for loops to iterate over a sequence of values or a range of values.
For example, the following code prints the integers in the range 1...10.
let range = 1...10
for number in range{
print(number)
}Another example could be iterating through an array and printing the elements:
var carMakesSecond = ["Toyota", "Honda", "Mazda", "Chevy"]
for item in carMakesSecond{
print(item)
}In Swift, we have an extra feature. If we have a situation where we are not using the variable a for loop gives us (number or item in the above examples), we can skip creating the unnecessary values. For example, if we want to do the same task 10 times, we can write the following code:
for _ in 1...10{
print("Doing the task!")
}Here, underscore skips create unnecessary values.
5.1.2. Looping through other Collections (Dictionaries, Arrays of Struct Objects, etc.)
Let's think about the following Dictionary:
This a dictionary for a car dealership where the keys are car brands and the values are the number of cars of the corresponding brands in their inventory. We want to loop through the dictionary and print the values from the dictionary.
We will look at some of the example outputs:
Code:
Output:
Code:
Output:
Code:
Output:
Long story short, we can use parenthesis to define which component to loop through selectively in a complex Collection.
Last updated
Was this helpful?