Loops
How to use a for loop to repeat work
Computers are made to do repetitive work. Swift uses loops to do things any number of times or once per item in a dictionary, array, or set.
Simple example:
let platforms = ["iOS", "macOS", "tvOS", "watchOS"] // This will run for each item in the platforms array for os in platforms { print("Swift works great on \(os).") }
Looping over a fixed range. Ex:
for i in 1...12 { print("5 x \(i) is \(5 * i)") }
Nested loops: Ex:
for i in 1...12 { print("The \(i) times table:") for j in 1...12 { print(" \(j) x \(i) is \(j * i)") } print() }
Ranges:
x...y
are inclusive of x and y
If you want to exclude y
. Ex:
for i in 1...5 { print("Counting from 1 through 5: \(i)") } print() for i in 1..<5 { print("Counting 1 up to 5: \(i)") }
This is called a half open range, meaning up to but excluding the last item.
The closed range means up to and including the last item.
There is also a one sided range 1...
that will operate until the end of the range. When using this version, we should check for the end of the range, or this could continue indefinitely.
The other variation of the one sided range looks like ...n
Sometimes you don’t want to use the loop variable. Ex:
var lyric = "Haters gonna" for _ in 1...5 { lyric += " hate" } print(lyric)
The underscore is a temp variable and is not used in the for loop.
Thought: Paul is absolutely 100% a Swifty (TS fan)
Scored 9/12 on For loops. A couple gotchas in the questions around data types.
Note: For loops can not be used on a dictionary.
How to use a while loop to repeat work
While loops will continue until the condition in question is met.
They are used way less than the for loop.
Basic syntax:
var countdown = 10 while countdown > 0 { print("\(countdown)…") countdown -= 1 } print("Blast off!")
This will continue iterating until the condition is met, then it will exit. Ex:
// create an integer to store our roll var roll = 0 // carry on looping until we reach 20 while roll != 20 { // roll a new dice and print what it was roll = Int.random(in: 1...20) print("I rolled a \(roll)") } // if we're here it means the loop ended – we got a 20! print("Critical hit!")
Note:
We use a for loop with a finite number of items, we use the while loop with an arbitrary amount of items – until the condition is met.
Scored 8/12 on while loops. Not great at guessing loop iterations without running them. 1x I clicked false on a question when I meant to click true. Another time, we were iterating over a counter that was a constant and I did not catch the mutation within the loop, hence an incorrect result.
How to skip loop items with break and continue
There are 2 ways to skip item(s) in a loop:
- break
- continue
We use continue
to continue to the next line in the loop after a condition is met. Continue continues the loop.
let filenames = ["me.jpg", "work.txt", "sophie.jpg", "logo.psd"] for filename in filenames { if filename.hasSuffix(".jpg") == false { continue } print("Found picture: \(filename)") }
We use break
to exit a loop immediately such that no more iterations are performed.
let number1 = 4 let number2 = 14 var multiples = [Int]() for i in 1...100_000 { if i.isMultiple(of: number1) && i.isMultiple(of: number2) { multiples.append(i) if multiples.count == 10 { break } } } print(multiples)
Labeled statements
Swift allows for labeled statements, in the case of nested loops in which an outer loop can be prefixed with a label in order to effect the outer loop once the inner loop matches some condition. Ex:
// This will continue running after the match is found for option1 in options { for option2 in options { for option3 in options { print("In loop") let attempt = [option1, option2, option3] if attempt == secretCombination { print("The combination is \(attempt)!") } } } }
// when the match is found, the outerLoop will be broken based on the use // of the labeled statement "outerLoop" outerLoop: for option1 in options { for option2 in options { for option3 in options { print("In loop") let attempt = [option1, option2, option3] if attempt == secretCombination { print("The combination is \(attempt)!") break outerLoop } } } }
Labeled statements: can also be used by the
continue
keyword
Scored 10/12 on exiting loops
Summary
if
is used to check whether a condition is true. You can pass any value but ultimately it must be evaluated to a Boolean.- To control the logic more, you can use
else
orelse if
- Conjunctions, that is comparing multiple values leverage either
&&
or||
- Using a switch allows you to avoid checking a variable multiple times in the casse of an
if/else
block fallthrough
will allow the following switch case to be evaluated- Ternary
?
allows us to check a condition and handle the truthy or false evaluation of the condition for
loops let us loop over arrays, sets, dictionaries, and ranges. Assign a loop variable or use the_
for a temp variablewhile
loops run until a condition is met or indefinitely if a check is not used to determine when it should end- we can skip some or all of a loop using
continue
orbreak