Swift Array – For Loop

To iterate over each element of a Swift Array, we may use for in loop, and access each element during respective iteration.

The following code snippet demonstrates how to use for loop with array, and iterate over each element of the array.

for element in array {
    //code
}

where array is the array of elements, and element contains that element of the array during that iteration.

Example

In the following program, we will take a string array, fruits, and iterate over each of the element using for loop.

main.swift

var fruits:[String] = ["Apple", "Banana", "Mango"]

for fruit in fruits {
    print(fruit)
}

Output

Swift String Array - For Loop

Now, let us take an array of integers, and iterate over this array using for loop.

main.swift

var fruits:[String] = ["Apple", "Banana", "Mango"]

for fruit in fruits {
    print(fruit)
}

Output

Swift Int Array - For Loop

Conclusion

Concluding this Swift Tutorial, we learned how to iterate over array elements using for loop in Swift.