Swift Introduction | Arrays and Dictionaries | Arrays and for-in Statements

You can retrieve and process array elements one at a time by specifying index numbers. When using an array to manage data, however, you often need to process every element in the same way.

For this purpose, use a for-in statement.

for variable in array {
    ...... process to perform ......
}

A for-in statement retrieves values from an array in order, assigns each value to a variable, and repeatedly executes the code inside the braces. By using that variable in the body, you can perform the same operation on every array element.

The following is a simple example.

let data:[Int] = [10, 20, 30]
var total:Int = 0
for num in data {
    total += num
}
println("total: \(total)")

This code retrieves every value from the data array, calculates the sum, and displays it. The statement for num in data retrieves each value from data in order and assigns it to num.