O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the for...in loop

The for-in loop iterates over a collection of items or a range of numbers and executes a block of code for each item in the collection or range. The format for the for-in statement looks like this:

for variable in collection/range {  
  block of code 
} 

As we can see in the preceding code, the for-in loop has two sections:

  • Variable: This variable will change each time the loop executes and will hold the current item from the collection or range
  • Collection/range: This is the collection or range to iterate through

Let's look at how to use the for-in loop to iterate through a range of numbers:

for index in 1...5 {  
  print(index) 
} 

In the preceding example, we iterated over a range of numbers from 1 to 5 and printed each ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required