Adam Rush

@Adam9Rush

22 November, 2021

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 ...

Sponsor

Subscribe for curated Swift content for free

- weekly delivered.