Day 4 - 100 Days of Swift

4 minute read

Loops

Day 4 covers all the loops. You look at for loops. You look at while loops. You look at repeat loops. You look at ways to break out of loops and ways to skip loops. And you look at infinite loops. But just the good kind that you intend to make, not the accidental ones.

For loops let you loop through all the items in a range or a sequence. They look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for i in 1..<4 {
    print("Number \(i)")
}
// Prints:
// "Number 1"
// "Number 2"
// "Number 3"

for friend in ["Joey", "Ross", "Chandler", "Monica", "Phoebe", "Rachel"] {
    print("\(friend) is a friend")
}

// Prints:
// "Joey is a friend"
// "Ross is a friend"
// "Chandler is a friend"
// "Monica is a friend"
// "Phoebe is a friend"
// "Rachel is a friend"

While loops have a condition that they check before each time through the loop and they continue looping while it is true:

1
2
3
while isFoodLeft {
    joeyKeepsEating()
}

Repeat loops have a condition that they check after each time through the loop, so they always run their code at least once, and they continue looping while that condition is true :

1
2
3
repeat {
    rossTalksAboutDinosaurs()
} while isAnyoneListening

There is a special keyword break that lets you break out of a loop early if you want:

1
2
3
4
5
6
7
while isRossWithRachel {
    if isOnBreak {
        print("Immediately sleeps with someone else...")
        break
    }
    print("Everything is going great.")
}

And if you are in a nested loop, you can name the outer one and break out of multiple loops at once:

1
2
3
4
5
6
7
8
9
10
11
outerLoop: for actions in thingsACatCanDo {
    for smell in thingsACatCanSmellLike {
        phoebesSong += "Smelly cat, smelly cat\n"
        phoebesSong += "you \(action) all day,\n"
        phoebesSong += "and you smell like \(smell)\n"
        let songLimit = (reasonableSongLimit + fortyFiveSeconds)
        if phoebesSong.count > songLimit {
            break outerLoop
        }
    }
}

There is also a continue keyword that lets you skip the rest of this run through the loop, and continue to the next one:

1
2
3
4
5
6
7
8
for item in monicasPantry {
    if today > (item.expirationDate + twoWeeks) {
        // tosses over shoulder
        continue
    } else {
        joey.eat(item)
    }
}

Since while loops run as long as their condition evaluates to true, if you want the loop to keep running until you want to break out of it, you can just give it true as the condition. Also works for repeat loops:

1
2
3
while true {
    monicaKeepsCleaning()
}

Reflections

I learned something new again today. I had no idea that you can name loops in order to break out of multiple loops. That is really cool. If I had to give a guess, I would probably say that, in general, it is best to structure your code so that you don’t need to use that feature, but it is cool that you can do it if you want to. I’m sure it’ll come in handy somewhere down the line.

I was a little nervous when I decided to start going through this series that I wouldn’t learn much. (I mean, I’m basically an expert in Swift already.) That since it is designed to let people pick up Swift from scratch, it would be too basic for me. But that was just my arrogance. I’m glad I decided to give it a shot, because I’ve already picked up a few things that I really didn’t know five days ago, and I’ll be a better developer because of it. Thanks Paul!