Swift

Loops

Looping through variables and more

While Loops

A lot of times, we don’t want code to execute just once if a condition is true. Instead, we want it to execute ‘while’ the condition is true, until the condition becomes false. This is where while loops come in handy. They basically run the code inside them until the condition is false.

var count = 0
while true {
    print("The count is now \(count)!")
    count += 1
    
    if count == 10 {
        break // ends the loop
    }
}
    
var numberIsNotZero = true
var count = 10
while numberIsNotZero { // same as writing numberIsNotZero == true
    print("The count is \(count)")
    count -= 2
        
    if count == 0 {
        numberIsNotZero = false //does the same thing as break, but with a variable controlling it instead
    }
}

For Loops

For Loops are just like While Loops, but they only run for a certain number of times. We can achieve this effect with while loops, but for loops are more flexible. Let’s try this first one:

for i in 1...5 {
    print("This loop has ran \(i) time!") 
}

The i is an Integer variable we create to keep control of how many times the loop runs, and in this case, 5 times. The 1...5 means to run from 1 to 5, which is inclusive. We will be messing with that in a bit, modifying it for usage with arrays.

If we don’t need to keep track of the count, we don’t need i. We can just add _ and it will run the same number of times, we just cannot keep track from the loop initialization.

for _ in 1...5 {
    print("This will print out 5 times!")
}

For Loops and Arrays

This is where for loops come in handy. We can modify what we used above and make a loop that prints out the data of the array. There are two ways to do this, with the first being the recommended.

var names = ["Greg", "Rodrick","Susan","Manny","Frank"]
for name in names {
    print(name)
}

This code finds the array called names, and each item becomes a “name”. Swift is smart, so it can figure this out easily, unlike some other languages. The other way to approach this is similar to other languages.

for i in 0..<names.count { // ..< means up to, so it's 1 minus the count of names, which is 5. 0,1,2,3,4; all indexes of our array.
    print(names[i])
}

Continue

What if we just want to exclude data and not completely end the loop? We can use continue to do this. Unlike break, continue skips over the rest of the code in the loop to the next running of the loop.

for name in names {
    if name == "Manny" {
        continue
    }
    print("\(name) is my favorite!")
}

In a later lesson, we will be going over switches, which are the faster way to use conditionals.

chevron_up