Chapter 6. Let computers do repetitive work

 

In this chapter you’ll learn how to make your app repeatedly perform an action using a loop.

This chapter covers

  • What are repetitions or iterations, and how are they used in programming?
  • What are loops, and how do you use the three types of loops?
  • Why do you need to repeat the same block of code multiple times?

Milestone 6, learn about loops, helps you write more efficient code. You’ve come a long way on your journey of programming in Swift. Chapter 1 gave you a head start. Chapter 2 introduced you to the user interface (UI). Chapter 3 taught you about the iPhone’s memory—as a matter of fact, the memory of most computers—and variables. You had hands-on experience with input/output (I/O) in chapter 4. Then chapter 5 made you feel like an app developer because you started to make apps decide, at runtime, what to do next based on data and situations.

Loops are constructs provided by Swift and other programming languages that allow you to run the same block of code a number of times.

Controlling repetition

Take a look at a loop you might perform in real life. You’re in physical-education class, and the teacher tells you to run three laps. As you run, you keep track of how many laps you’ve done. When you finish the third lap, you stop running. It’s important to know how many times you’ve gone around the track so that you don’t do too few laps or too many.

Here are some more real-life examples:

for-in loop statements

while loop statements

App: How Many Times?

Check your app knowledge

App-Exercise: Hang Your Word Upside-Down