Loops
Make the most repetitive tasks easier by learning Swift loops!
StartKey Concepts
Review core concepts you need to learn to master this subject
Ranges
Ranges
let zeroToThree = 0...3
// zeroToThree: 0, 1, 2, 3
Ranges created by the ...
operator will include the numbers from the lower bound to (and includes) the upper bound.
- 1Every day, we repeat a lot of things and we might not even think about it. For instance, when we cook, we might have to prepare our ingredients by chopping them up. We chop and chop and chop until …
- 2Before we get to writing our own loops, let’s explore what programming would be like if we couldn’t use loops. Let’s say we want to make a program that prints “Hip Hip Hooray!” 5 times: print(“…
- 3Now that we can appreciate what loops do for us, let’s start with the for-in loop. Below is the general syntax: for placeholderVariable in someSequence { for-in loop body } We use [for-in](ht…
- 4for-in loops also give us the flexibility to choose how we want to iterate over a sequence with the stride() function: stride(from: a, to: b, by: c) Notice, in order to use the stride() function…
- 5Aside from sequences of numbers, we can also loop over Strings! After all, a string is a collection of characters. Let’s say we wanted to look over a string and see if it contains “z”. In a progr…
- 6Remember our “Smelly code” chalkboard? Smelly code, or often referred to as having a code smell refers to bad progra…
- 7When iterating through a sequence, we might not need to use every single value. In these cases, it’d be nice to just tell our loop to skip a value. That’s where continue comes in. If we wanted to …
- 8Let’s say we need to find out what “respect” means in the dictionary. We would iterate through the pages of the dictionary until we found the word “respect” and read the definition. Although we had…
- 9Another loop we can use is the while loop. This loop allows us to continue iterating for as long as a condition remains true. while condition { // Execute while condition remains true } while…
What you'll create
Portfolio projects that showcase your new skills
Whale Talk
It's time to loop back to the fundamentals. Iterate through the characters of a string and use the vowels to construct your own "human speak to whale talk" translator.
99 Bottles of Milk
Write a Swift program that uses loops to print the lyrics of a very repetitive song!
Fizz Buzz
Write a program that prints the numbers from 1 to 100. But for multiples of 3 print "Fizz" instead of the number and for the multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz".
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory