Swift – Print Array Elements

In this Swift Tutorial, we will learn how to iterate through an array and print all the elements of the Swift Array.

To iterate and print all the elements of an Array in Swift, use for loop, while loop or forEach loop.

Example 1 – Print array elements using for loop

In this example, we have an integer array called primes. We use for loop to iterate through the array and print each element.

main.swift

var primes:[Int] = [2, 3, 5, 7, 11]

for prime in primes {
    print("\(prime)")
}

Output

2
3
5
7
11
ADVERTISEMENT

Example 2: Print array elements using while loop

In this example, we use for loop to iterate through the array and print each element. We also use the size of the array, array.count, to check the index between array size limits.

main.swift

var primes:[Int] = [2, 3, 5, 7, 11]

var i=0

while i<primes.count {
    print("\(primes[i])")
}

Output

2
3
5
7
11

Example 3: Print array elements using forEach

In this example, we have an integer array called primes. We use forEach to iterate through the array and print each element.

main.swift

var primes:[Int] = [2, 3, 5, 7, 11]

primes.forEach { prime in
    print("\(prime)")
}

Output

2
3
5
7
11

Conclusion

In this Swift Tutorial, we have learned how to print the elements of an array with the help of Swift example programs.