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 of the numbers to the console. This loop used the closed range operator (...) to give the loop a range to iterate through. Swift also provides the half-open range operator (..<) and the one-sided range operators that we saw in the previous chapter.

Now, let's look at how to iterate over an array with the for-in loop:

var countries = ["USA","UK", "IN"]  
for item in countries { 
  print(item) 
} 

In the preceding example, we iterated through the countries array and printed each element of the array to the console. As we can see, iterating through an array with the for-in loop is safer, cleaner, and a lot easier than using the standard C-based for loop. Using the for-in loop prevents us from making common mistakes, such as using the <= (less than or equal to) operator rather than the < (less than) operator in our conditional statement.

Let's look at how to iterate over a dictionary with the for-in loop:

var dic = ["USA": "United States", "UK": "United Kingdom","IN":"India"] 
 
for (abbr, name) in dic {  
  print("(abbr) --(name)") 
} 

In the preceding example, we used the for-in loop to iterate through each key-value pair of the dictionary. In this example, each item in the dictionary is returned as a (key,value) tuple. We can decompose (key,value) tuple members as named constants within the body of the loop. One thing to note is that, since a dictionary does not guarantee the order that items are stored in, the order that they are iterated through may not be the same as the order in which they were inserted.

Now, let's look at another type of loop, the while loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset