14.6 Array Iteration
The easiest way to iterate through the items in an array is to make use of the for-in looping syntax. The following code, for example, iterates through all of the items in a String array and outputs each item to the console panel:
let treeArray = ["Pine", "Oak", "Yew", "Maple", "Birch", "Myrtle"]
for tree in treeArray {
print(tree)
}
Upon execution, the following output would appear in the console:
Pine
Oak
Yew
Maple
Birch
Myrtle
The same result can be achieved by calling the forEach() array method. When this method is called on an array, it will iterate through each element and execute specified code. For example:
treeArray.forEach { tree in
print(tree)
}
Note that since the task to be performed for each array element is declared in a closure expression, the above example may be modified as follows...