Programming in Swift: Fundamentals

Oct 19 2021 · Swift 5.5, iOS 15, Xcode 13

Part 3: Control Flow

24. Nested Loops & Early Exit

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 23. Challenge: Iterating Collections Next episode: 25. Challenge: Nested Loops & Early Exit

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 24. Nested Loops & Early Exit

Update Notes: The student materials have been reviewed and are updated as of October 2021.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

Now, so far in this course, you've been working with loops that operate over full ranges. In other words, your loop always goes from start to finish with no interruption, but what if you don't want to finish the loop? What if you only wanna loop until you satisfied a certain particular condition and then get on with the rest of your program? Well, it looks like you need a break. Well, no, not that kind of a break, a break statement. The break statement lets you exit a loop early when you hit a particular condition so you don't have to waste time looping when it's no longer necessary. And you'll also find that you'll run into arrays that have an element or two that you don't wanna deal with or that you need to do some special processing for. So you can use the continue statement to tell Swift, "Hey, treat this element in a special way and then continue looping over the rest of the array." And you've also only dealt with single loops so far, but you can actually put a loop inside another loop if you have some advanced processing needs. Does that sound strange? Well, maybe a little, but once you see it in action, I think you'll see how useful nested loops can be in some scenarios. So again, open up the playground page for this video and get ready for a break. Um, I mean, you know what I mean. Sometimes you want to break out of a loop early and you can do that using the break statement, which immediately stops the execution of a loop and continues onto the code after the loop. Let's take the poolTemperature example from the last exercise. And since I'm leaving on vacation and flying to Alaska on Thursday, I really only want to see the temperatures up to and including Wednesday. So I create a four-loop for i in 0 to daysOfTheWeek.count. (keys clacking) But I don't want to print out anything once I hit Thursday so I'll add an if block before my print to check if the current element of the days of the week array has Thursday. (keys clacking) And then I simply put the brake instruction in there to tell Swift to exit the loop and move on before it prints anything. (keys clacking) I can run my playground. Now you can see that the console only prints out the days from Sunday to Wednesday. So notice that nothing else in this block of code executed? Swift immediately halted the execution of the code inside this block and carried on without printing anything else out. Let me put a little marker in there so you can tell the output from the different sections apart. (keys clacking) There. Now, sometimes you don't want to break. Instead, you want to do something special for a particular element inside that array. So let me construct a similar loop below. I'm just gonna cut and paste this loop since the code is so similar. (keys clacking) Now, if you're a music fan, you might know the old song by The Cure named "Friday I'm in Love". So I wanna print out "I'm in love" instead of the temperature when we encounter the Friday element. So change your if statement to this. (keys clacking) And instead of break, print out, "I'm in love". (keys clacking) And then immediately after that, put the continue statement to tell Swift to continue with the loop. (keys clacking) Execute playground again. And you'll see that once Swift encounters the Friday element, it printed "I'm in love" and continue told Swift to stop executing that code, but carry on with the next iteration through the loop. And that's the main difference between break and continue. Break stops the loop entirely while continue only stops the current iteration and then goes back to looping. Let me add another quick divider before I move on. (keys clacking) Now, nesting loop sounds a bit weird at first. Why would you wanna have a loop inside of a loop? Well, let me give you the example of a 10-story hotel, and I've just added five new floors to it. Floors 11 through 15. I can print out all the new floors in the hotel like this. (keys clacking) And if I execute that, I can see my new floors. Now think about how a hotel is constructed. Each floor has a set of rooms. Now my hotel has four rooms per floor; rooms one, two, three, and four. I want my room numbers to be the floor number and the room number together so I can tell guests to go to room 11-4 or 15-1. Now I need to print out all the new room numbers for the new floors in the hotel. So let me delete that print statement and I'll add another loop inside the existing loop to loop over the rooms. (keys clacking) And then I'll put a print statement in there to print out the floor and the room together. (keys clacking) I'll rerun my playground. There we go. So if you run your eye down the list, you can see how a loop runs through floor 11 first, then rooms one through four. Then the inner loop ends, and you go back to the outer loop for the next floor, 12. The inner loop then runs rooms one to four again, and then it repeats again all the way to floor 15. Now you can also use the break and continue statements inside of nested loops. Now I was all ready to put the room numbers on each door, but I just learned that we only ordered three beds for each new floor. So we're going to have to ignore the first room on each floor because of a bed shortage. That sucks. Okay. Well, I can skip printing room number one with a simple if statement and a continue statement just inside the room loop where I check if room is equal to four. (keys clacking) Now, if I rerun my playground, I can see that I only print out rooms two, three, and four, instead of all four. The continue statement here only breaks the inner loop. It doesn't affect the outer loop. So when you hit this continue condition here, Swift says, "Okay, I'm going to stop executing this code and move on." Where moving on means going to the next iteration of the outer floors loop. So am I ready to open my hotel? Well, not yet. I've just been informed of the 13th floor of the hotel is haunted. The hotel business is hard, man. Okay, so I want to not print anything when I get to the 13th floor, but I do want to go on and print room numbers for floors 14 and 15. Okay, that can be done with a continue statement in the outer loop right here. We check to see if floor is equal to 13. (keys clacking) And if it's true, then continue. (keys clacking) I'll rerun my playground again. Okay. So now the console only prints out floors 11, 12, 14, and 15 and only rooms two, three, and four on each floor. Okay, there. I think we're ready to open this hotel. Oh, wait. Okay. Apparently, the staff lost some of the pieces to assemble the beds in rooms 12-3 and 12-4 so we can't open those rooms either. So basically, once I hit room 12-3, I need to just get out of the inner loop and not print the rest of the rooms on floor 12. Okay, so let me check for that condition with a Boolean operator. If floor is equal to 12 and room equal to three, I want to continue. So let me check for that condition with a Boolean operator. If floor is equal to 12 and room is equal to three, I want to continue. (keys clacking) Let me execute my playground again. Oh, wait. That's not quite right. It's only continuing the inner loop and printing room 12-4, but I wanna get out of the inner loop and continue the outer loop instead so that it doesn't print 12-4. So I can use labeled statements to tell Swift exactly where I want to continue execution. All I need to do is add a label to the beginning of each of my loop statements like so. (keys clacking) Now I can say continue floor loop here to tell Swift to stop the inner loop and continue with a labeled outer loop. (keys clacking) Run my playground again. There! Finally! Time to kick off the grand opening of this hotel with some champagne. (champagne cork popping) You've covered a lot in this video. Good job, you. If you're not too pooped from loops, head on to the next video where I've got a few challenges for you to see if you really understand nested loops, break, continue, and labeled statements. I'll see you there.