In Swift, if you want to iterate over a sequence, such as an array or ranges of numbers, you can take advantage of the for-in
loop. Not only performant but super readable too.
Arrays
Take a look at this example:
let sports = ["๐", "โฝ๏ธ", "๐", "๐พ", "โณ๏ธ"]
for icon in sports {
print(icon)
}
In your code above, you have an array of sports icons, and you’re looping through the array using a for-in
loop and print each icon.
Your console will print:
๐
โฝ๏ธ
๐
๐พ
โณ๏ธ
Dictionaries
You can also imply the same logic for dictionaries.
let sports = ["๐": "Rugby", "โฝ๏ธ": "Football", "๐": "Basketball", "๐พ": "Tennis", "โณ๏ธ": "Golf"]
for (icon, name) in sports {
print("\(icon) is called \(name)")
}
You have a dictionary that contains both the icon and the name of the sport. You’re accessing both key and value within the for-in
loop.
Your console will print the following:
๐ is called Rugby
โฝ๏ธ is called Football
๐พ is called Tennis
โณ๏ธ is called Golf
๐ is called Basketball
If you run this many times, you’ll notice that the order is always different. This is because Dictionaries are unordered by default.
Numeric Ranges
A for-in
loop is super powerful because you can also utilise these for numeric ranges.
Take this example:
for index in 1...10 {
print("\(index) times by 2 is \(index * 2)")
}
In this example, we are iterating between 1 and 10, and each time is running a multiplication of 2.
Your console will look like this:
1 times by 2 is 2
2 times by 2 is 4
3 times by 2 is 6
4 times by 2 is 8
5 times by 2 is 10
6 times by 2 is 12
7 times by 2 is 14
8 times by 2 is 16
9 times by 2 is 18
10 times by 2 is 20
The range will begin at 1 and end at 10 inclusively, and this is denoted with the use of the ...