Loops and indexes
There are four ways to walk an array (its values, its indexes, both, or backwards), and the job says which before you type.
- Reach for it when
- Always. Every tool below is one of these loops with something added.
- The move
- Four loops: over the values, over the indexes, over both, and backwards. Know which one a job needs before you type.
- Cost
- One loop over n things is n steps.
The idea
A postman fell off the end of my street this morning.
Streets are usually clear about where they stop.
This one was. He had other instructions. We'll come back to him. This is the first lesson, Arthur. What's in it?
The for loop.
The people reading this build apps for a living. They've typed for ten thousand times.
Then this will feel easy, and it's meant to. Every step in the course adds one small thing to the step before it. If a step ever feels hard, we made it too big. That's our mistake, not the reader's.
So what's the one small thing today?
Choosing the loop before you type it. There are four.
Give me a picture.
An array is a street. Each house has a number on its door and something inside. The door number is the index. What's inside is the value. The loop is a postman walking the street.
And the four?
He can knock at every house and never read a door number. He can read every door number, and knock where he needs to. He can do both at each house. Or he can start at the last house and walk back.
How do I choose?
Ask what the job needs. What's inside: the values. Where something is: the door numbers. Both: both. Last house first: backwards.
And the door numbers start at 0? So five houses are numbered 0 to 4, and there's no number 5?
There is no number 5. People go looking for it all the same.
What if he wants every second house? Or wants to stop at the first dog?
Those are ways to change a walk. There are three. stride takes longer steps. break ends the walk: he has met the dog and he is going home. continue skips one house and carries on.
And who tells him where the street ends?
The street does, if you let it. He only gets lost when somebody types the end of the street by hand.
Somebody did. Hold that thought. It ends in a hedge.
That is the whole tool: four walks, three ways to change a walk, and at the end one walk inside another. Most later lessons are one of these loops with something added, so choosing the loop has to cost you nothing. The while loop is not here. It arrives with the first lesson that needs it.
The shape
This is what you know by heart: the four walks. Here they are in one function, each writing down what it is handed.
/// What each of the four loops is handed, pass by pass.
func fourWalks(_ numbers: [Int]) -> [String] {
var seen: [String] = []
for number in numbers { // the values
seen.append("\(number)")
}
for i in numbers.indices { // the indexes
seen.append("\(i)")
}
for (i, number) in numbers.enumerated() { // both
seen.append("(\(i), \(number))")
}
for i in numbers.indices.reversed() { // the indexes, last one first
seen.append("\(i)")
}
return seen
}Each walk has its job.
- The values.
for number in numbershands you what is inside each house, from the first house to the last. It has no door number in it, so it has no door number to get wrong. Reach for it first. - The indexes.
for i in numbers.indiceshands you each door number, and you knock withnumbers[i]. Take it when the job has to know where: to say which house, or to change what is inside one. - Both.
for (i, number) in numbers.enumerated()hands you a count from 0 and what is inside, together. Along a whole array the count is the door number. Take it when the body needs both. - Backwards.
for i in numbers.indices.reversed()hands you the same door numbers, last house first. Take it when the job starts at the far end.
None of the four says where the street ends. The array knows, and it tells the loop. So none of them can walk off the end.
Watch it run
The street is 7, 0, 8, -3 and 6. Here is what each of the four loops is handed on each pass.
| pass | number | i | (i, number) | i, backwards |
|---|---|---|---|---|
| 1 | 7 | 0 | (0, 7) | 4 |
| 2 | 0 | 1 | (1, 0) | 3 |
| 3 | 8 | 2 | (2, 8) | 2 |
| 4 | -3 | 3 | (3, -3) | 1 |
| 5 | 6 | 4 | (4, 6) | 0 |
Look at the last row. There are 5 houses, and on the fifth pass i is 4, not 5. The door numbers start at 0, so the last one is always the count less one. The mistake that sends a loop off the end of an array is that row forgotten.
Step by step
Add up an array with for number in numbers
/// The sum of `numbers`. An empty array adds up to 0.
func sum(_ numbers: [Int]) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}What is new: the first walk, with a variable that collects as it goes. for number in numbers hands you what is inside each house in turn, and total takes it in. For 7, 0, 8, -3 and 6 the sum is 18.
total starts at 0 because nothing has been added yet. On an empty street the loop does not run even once, so the answer is that 0: the sum of no numbers is 0. Nothing had to be written for the empty array.
Add it up again with for i in numbers.indices
/// The sum of `numbers`, found by walking the indexes.
func sumByIndex(_ numbers: [Int]) -> Int {
var total = 0
for i in numbers.indices {
total += numbers[i] // knock at door number i
}
return total
}What is new: the loop hands you a door number, and you knock for yourself with numbers[i]. numbers.indices is every door number of the street in order, here [0, 1, 2, 3, 4]. The sum is 18 again.
For a sum this is more typing for the same answer. The walk earns its place when the job has to know where.
You will often see it written for i in 0..<numbers.count. That visits the same door numbers, with the end typed by hand. ..< leaves its end out, which is right: the count is 5 and the last door number is 4. Its twin, ..., lets its end in: 0...4 is the same five door numbers. An end that is typed can be typed wrong, one house too far or one too few. numbers.indices has no end to type.
Print each index beside its value with enumerated()
/// One line for each number: its index, a colon, a space, and the number.
func indexedLines(_ numbers: [Int]) -> [String] {
var lines: [String] = []
for (i, number) in numbers.enumerated() {
lines.append("\(i): \(number)")
}
return lines
}What is new: both at once. enumerated() hands you a pair at each house: a count that starts at 0, then the value. Along a whole array that count is the index.
The function hands back the lines it would have printed, as strings, so that they can be checked. For the five houses it gives ["0: 7", "1: 0", "2: 8", "3: -3", "4: 6"].
The pair is the count first and the value second, whatever you name them. for (number, i) in numbers.enumerated() compiles, and the first line comes out as "7: 0" where it should be "0: 7". In an array of Int both halves are Int, so the compiler has nothing to complain about further down the body either.
Walk an array backwards
/// The numbers from the last to the first.
func backwards(_ numbers: [Int]) -> [Int] {
var lastFirst: [Int] = []
for number in numbers.reversed() {
lastFirst.append(number)
}
return lastFirst
}What is new: reversed() turns a walk round. Here it turns the first walk, and hands you the values, last house first. The function gives [6, -3, 8, 0, 7].
It turns the walk over the door numbers as well. That is the fourth walk of the shape: numbers.indices.reversed() is [4, 3, 2, 1, 0]. Take it when the job has to know where.
/// One line for each number, the last number first:
/// its index, a colon, a space, and the number.
func indexedLinesBackwards(_ numbers: [Int]) -> [String] {
var lines: [String] = []
for i in numbers.indices.reversed() {
lines.append("\(i): \(numbers[i])")
}
return lines
}This gives ["4: 6", "3: -3", "2: 8", "1: 0", "0: 7"]. Each house keeps its own door number.
Take care if you reach for enumerated() here, because the order of the two calls matters. numbers.enumerated().reversed() pairs first and turns round after, so the last house is handed over as (4, 6). numbers.reversed().enumerated() turns round first and counts after, so the last house is handed over as (0, 6). enumerated() counts. It does not read door numbers.
Visit every second element with stride(from:to:by:)
/// The numbers at indexes 0, 2, 4 and so on.
func everySecond(_ numbers: [Int]) -> [Int] {
var picked: [Int] = []
for i in stride(from: 0, to: numbers.count, by: 2) {
picked.append(numbers[i])
}
return picked
}What is new: a walk whose step you choose. stride(from:to:by:) takes three things: the door number to start at, the door number to stop before, and how far to step each time. Here it visits door numbers [0, 2, 4] and gives [7, 8, 6].
to: stops before its number, the way ..< does. That makes to: numbers.count safe, because the count is never a door number. Its twin, stride(from:through:by:), lets its number in, the way ... does. stride(from: 0, through: numbers.count - 1, by: 2) visits the same door numbers, [0, 2, 4].
One more small thing: a stride can go down the street. What is new is a by: below zero.
/// The numbers from the last to the first, by way of `stride`.
func backwardsByStride(_ numbers: [Int]) -> [Int] {
var lastFirst: [Int] = []
for i in stride(from: numbers.count - 1, through: 0, by: -1) {
lastFirst.append(numbers[i])
}
return lastFirst
}It starts at the last door number, numbers.count - 1, and goes down one house at a time. The end is now house 0. House 0 is a real house and has to be visited, so it is through: 0. The function gives [6, -3, 8, 0, 7], the same as step 4. With to: 0 the walk stops before house 0 and gives [6, -3, 8, 0]: the 7 never arrives.
One rule covers both directions. through: names the last door number the walk may visit. to: names the first number it may not.
Stop at the first negative number with break
/// The numbers that come before the first negative one.
func beforeFirstNegative(_ numbers: [Int]) -> [Int] {
var kept: [Int] = []
for number in numbers {
if number < 0 {
break // the walk is over
}
kept.append(number)
}
return kept
}What is new: break ends the walk it is in. Nothing more of the loop runs: not the rest of this pass, and no later pass. The function carries on at the line after the loop. For 7, 0, 8, -3 and 6 it gives [7, 0, 8]. The -3 is the dog. The 6 is never visited, though there is nothing wrong with it.
The test comes before the append, so the negative number is not kept. And 0 is not below zero, so the walk goes past the 0.
Skip the zeros with continue
/// The numbers that are not zero.
func withoutZeros(_ numbers: [Int]) -> [Int] {
var kept: [Int] = []
for number in numbers {
if number == 0 {
continue // not this house: on to the next
}
kept.append(number)
}
return kept
}What is new: continue ends this pass only. The rest of the body is skipped for this house, and the walk goes on to the next. For the same street it gives [7, 8, -3, 6].
The two words sit in the same place and are easy to swap. Say them the way the postman would. break: I'm going home. continue: not this house.
Visit every pair of positions i < j with one loop inside another
/// Every pair of indexes `i < j`, each pair once.
func everyPair(_ numbers: [Int]) -> [[Int]] {
var pairs: [[Int]] = []
for i in numbers.indices {
for j in (i + 1)..<numbers.count { // only the houses after house i
pairs.append([i, j])
}
}
return pairs
}What is new: a walk inside a walk. For each house i, a second walk visits only the houses after it, so j starts at i + 1. Each pair of houses is met once, with the lower door number first, and no house is paired with itself.
For a street of three it gives [[0, 1], [0, 2], [1, 2]]. The five houses make 10 pairs, and this is where they come from:
i | the js it meets | pairs |
|---|---|---|
| 0 | 1, 2, 3, 4 | 4 |
| 1 | 2, 3, 4 | 3 |
| 2 | 3, 4 | 2 |
| 3 | 4 | 1 |
| 4 | none | 0 |
4 + 3 + 2 + 1 + 0 is 10. Look at the last row. When i is the last house, (i + 1)..<numbers.count is a range with nothing in it, and the inner loop does not run. Nothing has to guard against that.
The inner walk starts part of the way along the street, so this time its end has to be typed, and ..<numbers.count is the end to type. With ...numbers.count - 1 the range for the last house would run from 5 to 4. Swift will not build a range that runs backwards. It stops the program.
Often the job is to count the pairs, not to keep them. What is new: a counter in place of the list.
/// How many pairs of indexes `i < j` there are.
func countOfPairs(_ numbers: [Int]) -> Int {
var pairCount = 0
for i in numbers.indices {
for _ in (i + 1)..<numbers.count {
pairCount += 1
}
}
return pairCount
}The inner loop's variable is _ because nothing reads it. For the five houses the count is 10. Ten houses make 45 pairs and a hundred make 4,950: the pairs grow much faster than the street does. The lesson "How the work grows" starts from there.
What goes wrong
One house too far. ... lets its end in. for i in 0...numbers.count visits door numbers [0, 1, 2, 3, 4, 5] on the street of five. There is no house 5, and the program stops with "Index out of range".
One house too few. for i in 0..<numbers.count - 1 visits [0, 1, 2, 3] and leaves out the last house. Nothing stops. The sum comes out as 12 where it should be 18. A wrong answer that looks like an answer is the worse of the two.
An empty street. The four walks and both strides pass an empty array without running once. A loop over a range that ends at numbers.count - 1 never starts. For an empty array that end is -1. Swift will not build a range from 0 to -1, and the program stops with "Range requires lowerBound <= upperBound".
to: and through: the wrong way round. Going down, to: 0 leaves out the first house, as step 5 showed. Going up in twos, stride(from: 0, through: numbers.count, by: 2) visits [0, 2, 4] on the street of five, which is right by luck. On a street of four it visits [0, 2, 4], and there is no house 4. A mistake that only shows on even counts is hard to find.
break and continue the wrong way round. Skipping the zeros with break gives [7]: the walk ends at the first zero, and everything after it is lost. Stopping at the first negative number with continue gives [7, 0, 8, 6]: the -3 is stepped over, and the walk carries on to the 6.
A break that ends less than you meant. break ends only the walk it is in. Put one in the inner walk of step 8, after its first pair, and the outer walk still goes on to every house: the pairs are [[0, 1], [1, 2], [2, 3], [3, 4]]. And inside a switch, break leaves the switch, not the walk. Step 6 with its test written as a switch gives [7, 0, 8, 6]: the walk never stopped.
Starting the inner loop in the wrong place. With j starting at i, each house is paired with itself as well, and five houses give 15 pairs. With j starting at 0, every pair is also met twice, once each way round: 25. Start j at i + 1.
Reaching for the indexes out of habit. If the body only ever reads numbers[i], the job needs the values, and for number in numbers has no door number in it to get wrong. A walk over the indexes has one. Write total += i in step 2, and the street adds up to 10: its door numbers, not what is inside them. Choose the walk first. Then type.
Say it back
What are the four walks, and what does each hand you?
Show the answerHide the answer
for number in numbers hands you the values. for i in numbers.indices hands you the indexes. for (i, number) in numbers.enumerated() hands you both. for i in numbers.indices.reversed() hands you the indexes, last one first.
How do you choose between them?
Show the answerHide the answer
Ask what the job needs, before you type. What is inside: the values. Where something is: the indexes. Both: enumerated(). Last house first: reversed().
An array holds five numbers. What is its last index, and why does 0...numbers.count fail?
Show the answerHide the answer
It is 4, the count less one. ... lets its end in, so the loop asks for numbers[5], and there is no house 5.
Which stride lets its end in: to: or through:?
Show the answerHide the answer
through:. to: stops before its number. So going up it is to: numbers.count, and going down it is through: 0.
What does break do, and what does continue do?
Show the answerHide the answer
break ends the walk it is in. continue ends this pass, and the walk goes on to the next house.
In the loop inside a loop, why does j start at i + 1, and how many pairs do five houses make?
Show the answerHide the answer
So that each pair is met once and no house is paired with itself. Five houses make 10 pairs.
Why did the postman fall off the end of the street?
Show the answerHide the answer
Someone typed the end of the street by hand: for i in 0...numbers.count. Five houses are numbered 0 to 4, and he was sent on to number 5, which is a hedge. numbers.indices would have let the street tell him where it stops.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Add up an array | Easy |
| 2 | Add it up by index | Easy |
| 3 | The last number is left out | Easy |
| 4 | Off the end of the array | Easy |
| 5 | Each index beside its value | Easy |
| 6 | Walk an array backwards | Easy |
| 7 | The lines, last one first | Easy |
| 8 | Every second number | Easy |
| 9 | The first number never arrives | Easy |
| 10 | Stop at the first negative number | Easy |
| 11 | Skip the zeros | Easy |
| 12 | Everything after a zero is lost | Easy |
| 13 | Every pair of positions | Easy |
| 14 | How many pairs? | Easy |
| 15 | A position paired with itself | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.