7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
FREELessons: 30Length: 4.8 hours

Next lesson playing in 5 seconds

  • Overview
  • Transcript

4.2 Looping

Conditionals are one fundamental part of controlling the flow of your application. Another control flow construct you will need is the loop—operating sequentially on the elements of collections. In this lesson we will focus on looping through collections with the different types of for loops and while loops.

4.2 Looping

The next basic way on how you can actually control the flow of your application is through something called loops. Now, loops are no really different than other programming languages that contain loops. As within the Swift language, but there are a couple of little nuances here that I want to cover. So the first basic type of loop is known as a for loop. Now there's two different variations on this. There is the standard for loop, as well as the for in loop. So let's quickly take a look at both of these different types of for loops. So let's say that I had an array of numbers. So I could say let numbers = and we'll just put in some numbers in here just to have some sample data. And now let's say I wanted to loop through all of these. I wanted to go through all the values available in my collection. Now it's important for you to kind of pay attention to that because this is going to become very important as you start to find different collection types,whether they be arrays or sets or dictionaries or some other things out there. A lot of times you're gonna have to go working through them and iterating through all of the values in there and doing some sort of operation. And it's very important to understand the basics of these loops because this is your bread and butter when it comes to being able to iterate over all these different collection types. So but for this case we're just going to use a simple array as an example. So I have an array of numbers here, and I want to loop through all of them. I want to do something very simple. So let's say I just wanted to output all of them. So I can use a standard for loop. So I could say for. And if you've ever done any sort of for loops in other languages, it's going to seem quite similar. I could say for var Index = 0. So I'm going to say for some sort of variable that I'm going to use to iterate over all the indexes found in my array. And then I do a ;. And then after that I specify the condition that's going to be checked every time we go through through our loop. So I want to make sure that this runs as long as index is less than numbers.count. And then, each time a iteration completes. I want to increase my index, my counter value, by one. So now I've done three things. I've created my counter that's going to iterate all through the indexes of my numbers array. I have a test here that's going to check the values for that index to see how many times it's going to run. So this loop is going to continue to run as long as index is less than the numbers. The count of the numbers that are found in my array, and after I've done each iteration I'm going to increment that counter, and then I'm once again going to use the open close curly braces and now I can do whatever operation in here that I want. And I'll just keep it pretty simple here I'm just going to print out a line and I'll say the number is, and I'll use string interpolation again here and I'll say numbers Index. Just like that. So now I can save this, and if I were to run my application. You'll see my build succeeded. And I have here the number is 1, 2, 3, 4 and 5. So you can see I started at index 0, because remember the indexes found in arrays and other collections start at 0. So at 0, 1, 2, 3 and 4, so you see that I have incremented my index over all the different iterations there. And it kept running until the last time where index was actually equal to five, because if I were to let that go I would have gotten out of bounds exception. But just to show you that, I could actually change this to not necessarily just be a less than, I could change it to be equal to. So we'll save that and if I were to run it now you'll see, it'll run a few times, and then it'll actually blow up on me because the array index was out of range, which means index is actually equal to five. But I only have indexes of zero, one, two, three, and four. So I tried to get the next one, and it wasn't there. So it's something to definitely watch out for. So another way to iterate over this, and I'm actually going to use my comments here again. Another way to iterate over a collection, in this case an array, but you could do it similarly for sets and dictionaries, is to use the for in loop. So the structure is a little bit different. And we're not going to be talking about indexes this time, we're just going to say, just give me all of the values in there one of the time and I'm going to do something with them. So the way that we do that is we're going to specify four, and now we're going to give a variable name that we want to use to refer to each of the individual values found within our collection. So I'll say for num. And then we use the in keyword. So there's our for in. And we'll say for in numbers (). Now within here I can do anything that I want. So this time I can do something similar here, where I could simply print out a line here. I'll copy and paste this here. In this case, instead of interpolating the numbers with an index, I can simply refer to each of those individual numbers as the Num variable that I defined right here. And I can run my application and once again you see that I have the number is 1,2,3,4, and 5. So I don't have to worry about that array index out of bounds exception anymore cuz I'm not dealing with those indexes anymore. So that's the basic process of how you're gonna use the for and the for in. Now you're gonna see another variation of the for in which is relatively new into the world of Swift. And that has to do with the fact if I'm creating a for loop here and I don't necessarily care about a value that I'm getting, or maybe that I would be using as an index. So let me give you a very quick example. Let's say we're building a simple calculator. And we want this calculator to be able to calculate exponents. So let's say I wanted to take the number two and raise it to the power of eight so I wanted to multiply two by itself eight times. How can we do something like that? Well let's start off with a number, so let's say we're going to let the number = 2. We're going to let the power = something arbitrary, so just pick 8 for this, but you could select pretty much anything you'd want. And then we want to calculate the answer. What's the value after I multiply 2 by itself 8 times? So, we're going to create a variable. That's gonna contain the answer and this is gonna be a counter that we're gonna run through over and over again to continue to increment. So we're gonna start it off to be =1. Because if you think about it two raised to the zero power is gonna be one. And then everything else after that is gonna multiply by that value. Two times. So now we're going to go ahead and create another loop so how do we do that? Knowing what we know now, based on the for and the for in loops how can we do something like this? Well, we could do something like for, and I could do the standard for loop but I am a little bit more of for in type of fan. So let's say I wanted to do for each of the numbers that I find in. But how am I gonna specify this, cuz I'm not really dealing with collections anymore? Well, there's a special way that we can start to refer to collections or refer to a range of data. And ranges are a very common thing that you're gonna find within Swift and they're very powerful and we'll continue to use them as we go on throughout the course. But the basic idea behind them is I can specify a range of data, a starting point and an ending point. And I can just specify this in a very simplistic in a very short way to say I want to go from one value up to the next. So in my case, I want to start with the value one, and then I want to specify the range from one up to the value that's stored in power. And the range is specified by the ellipsis, or three periods. Now there's a variation on that, and I'll show you that in just a second. So I want to say I want to grab all the numbers that are in the range from one up to power, so now I can do my opening close curly brackets and all I want to do and here is I want to go ahead an increment answer. I want to do the multiply equals and I'm going to do that by number. So now at this point I'm going to run over this eight times, because I'm going to start at one and I'm going to go up to power, and this is basic ellipsis right here is going to say this is all inclusive. I want to include the first value which is one and I want to include the last value which is going to be eight. Now there's another variation on this where you could actually do two periods and a less than sign which is going to work somewhat similarly except with the for the fact that it's going to start at one and it's not going to go all the way up to eight so it would actually stop at seven. But in this case I want to go all the way up to eight, so I'm going to save that and then I'm going to come down here and I'm going to say print a number to the power of power is answer. So I'll just go ahead and slap my string interpellation in here like that. And go ahead and save and we'll run. And we'll get out here that to the power of 8 is 256. So there you have it. Now, one thing you're going to look at this really quickly, is you're going to say well why did I need this variable here? I didn't actually use it for anything. And that's a very good point. And you will on occasion running the scenarios where that's going to happen and Swift is actually introduced a new concept where you can actually say, you know what? I want to iterate all through all of these things, but I don't really need to create a variable. So just kind of skip that part and let me do my processing here. And the way that we do that is actually within underscore. So that underscore is going to say, yeah I do want to use a for in loop, and I want to iterate over this range, but I don't really care what the values are. I just need to run it a certain number of times. So I could go ahead and run that, and it's still going to work. We're going to get 2 to the power of 8 is 256. So that's the basic process of using the for loops. So let's go ahead and expand this a little bit more. And we are going to talk a little bit about a second type of loop which is actually going to be the while loop. And a while is somewhat similar to the for loop, but it's a little less verbose in the way that you're going to define it. So the way to this is gonna work is I'm going to create a variable here. We'll just call it value, and we'll set it = 0. Now I want to do some sort of operation. While value is something or while some other conditional check is true, so I could say while. In our case I want to maybe run this while value is less than five. So we'll go ahead and use that is our condition. So our condition goes right here after the while key words. We're going to check to see while value is less than five, then we want to run this particular block of code. So we're, once again, do something simple here. We'll just say print, the value is, we'll put in here, value, like this, and we will go ahead and save it. Now you will be tempted to run this. And I am going to try to run this, but you're gonna see that this is just gonna continue to go and you're gonna see all these little counters go off the charts. So I'm gonna stop this. And the reason that this is happening is because with a while loop you save a little bit of verbosity on the definition of the loop where all you have to do is say while and that defines some sort of condition. But unlike the for loop where we specified how we want to increment the counter or the thing that we're checking, for the while loop we didn't. So for a while loop you actually have to do your operation and then you have to be adjusting values as you go to make sure that you're not going to run into what's known as an infinite loop like we just saw. So now I can run this. And it's only going to go up to 0, 1, 2, 3, and 4, because as soon as value had 5, we popped out of our little loop here. And we were done with that particular while loop. Now there's another variation on the while loop that you can play around with as well. And you may have heard of it in other languages, referred to as the do while loop where you would do something like do. And then create some sort of block of code here in then you would do while, but with Swift 2.0 they've actually changed that. So do is actually used for other purposes now. Now the do loop has been replaced with the repeat while. So, while that does seem a little bit more explicit about what's going on here, I'm not a huge fan simply because it's really going against everything that I've ever learned in other programming languages that did do while loops. Now I have to relearn what it's called in the Swift language, but it is what it is. So the way that this is going to work is it's actually going to repeat a certain block of code here, and then it's gonna check the while condition. So instead of doing while and then executing something, it's doing the inverse. So now are once again gonna start with value = 0, or actually in this case we can make it a little bit more interesting. We can say while value = 6. I'm going to do the same operation here, so go ahead and copy this and we'll stick it in here, but we'll still have our conditional check here be while value is less than five. So we'll go ahead and save this, and what's gonna be interesting here is if I were to run this now, it's actually gonna fire the first time. So we'll see the value of six, so you can see we're going to run our operation first and then start checking. So it's a little bit of a different way to look at it, looking at it from a different perspective. But there are definitely use cases out there where you're gonna need to do something like this. Where you absolutely need to run some sort of block it code at least once. And then you can start worrying about the conditional statements and the while clause itself. So that's the basics of creating loops using the for, the for in, the while, and the repeat while. And now you're really starting to get a lot of information that's going to allow you to really start to write some very nice applications. That are going to allow you to do some conditional checking and loop through some values and stuff like that. But before we actually write a demo application to use all of these new things that we're learning, there's a couple new features that have been introduced into Swift in 2.0 that are going to further assist you with your controlling of the flow of your application. And we're going to talk about those next.

Back to the top