For Loops in Swift 4

Chiamaka Nwolisa
2 min readDec 3, 2017

--

I started learning Swift a few weeks back and coming from JavaScript, I always get confused about somethings. I intermittently carry some patterns from JS over to Swift unconsciously, the for loop in JS is one of those things.

If you know JS, you recognise this as the way for loops are written

for (let i=0; i<=5; i++) {   
...
}

Well, this is not the way for loops are written in Swift. Sorry

From my studying, I have been able to craft out 3 ways to use for loops in Swift.

1. Looping over arrays

If you want to loop over an array, this is how you would be able to accomplish that using Swift.

let names = ["Anna", "Sam", "Smith"]   
for name in names {
...
}

The snippet above loops over the names array and assigns every item in the array to the variable name and lets you use it in the block.

2. Looping over a dictionary

A dictionary is an unordered collection of key-value pairs.

["spider": 8, "ant": 6, "cat": 4] is a dictionary with keys spider, ant, cat & values 8, 6 and 4 respectively

Looping over the dictionary is as easy as doing this:

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
//animalName: spider
//legCount: 8
//....
}

Imagine a scenario where you need to add up all the values in the array, this is an easy way to accomplish that.

3. Looping with numeric ranges

Sometimes, you want a normal for loop like the JS snippet up top. In Swift, its ridiculously easy to accomplish that using numeric ranges.

for index in 1...5 {
...
}

The above snippet says, iterate over the range starting at 1 and inclusive of 5 i.e from 1–5

The inclusive part is being determined by the number of dots between both numbers. There are 3 dots which signifies that it should loop from 1 to 5.

If you do not want 5 included, you use this called the half-open range operator (..<).

for index in 1..<5 {
...
}

This would loop from 1 to 4 and stop execution.

NOTE: You might not care to use the index when looping with numeric ranges. You can ignore the index variable by substituting it with an underscore (_)

for _ in 1...5 {
...
}

Also published on my blog

Say Hello on Twitter ☺️

--

--