Iterating over an array

We can iterate over all elements of an array, in order, with a for-in loop. The for-in loop will execute one or more statements for each element of the array. We will discuss the for-in loop in greater detail in Chapter 4, Control Flow and Functions. The following example shows how we would iterate over the elements of an array:

var arrayOne = ["one", "two", "three"]  
for item in arrayOne { 
  print(item) 
} 

In the preceding example, the for-in loop iterates over the array and executes the print(item) line for each element in the array. If we run this code, it will display the following results in the console:

one  
two  
three 

There are times when we would like to iterate over an array, as we did in the preceding example, but we would also like to know the index, as well as the value of the element. To do this, we can use the enumerated method of an array, which returns a tuple (see the Tuples section later in this chapter) for each item in the array that contains both the index and value of the element. The following example shows how to use this function:

var arrayOne = ["one", "two", "three"] 
for (index,value) in arrayOne.enumerated() { 
  print("(index) (value)") 
} 

The preceding code will display the following results in the console:

0 one 
1 two 
2 three 

Now that we have introduced arrays in Swift, let's move on to dictionaries.

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

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