Chapter 6. Loops

Loops help with repetitive tasks. They execute a set of code repeatedly, either for a given number of iterations or for as long as a defined condition is met. Loops can save you from writing tedious and repetitive code, and you will use them a lot in your development.

In this chapter, you will use two sorts of loops:

  • for loops

  • while loops

for loops are ideal for iterating over the elements of an instance or collection of instances if the number of iterations to perform is either known or easy to derive. while loops, on the other hand, are well suited for tasks that execute repeatedly as long as a certain condition is met. Each type of loop has variations.

Let’s start with a for-in loop, which performs a set of code for each ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.