Swift – Print Array Elements
In Swift, you can print every element of an array by iterating over the array with a for-in loop, a while loop, or the forEach method. You can also print the complete array in one statement, include array indexes in the output, or join string elements into a formatted line.
To iterate and print all the elements of an Array in Swift, use for loop, while loop or forEach loop.
Print Every Swift Array Element Using a for-in Loop
A for-in loop is the most direct option when you need to process each array element in order. The loop assigns each element to a temporary constant and executes the loop body once for that element.
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
Each call to print() adds a newline by default, so every number appears on a separate line.
Print Swift Array Elements Using a while Loop
A while loop is useful when you need explicit control over the array index. Start at index 0, continue while the index is less than array.count, and increment the index after printing each element.
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
The loop shown above does not increment i, so it would repeatedly print the first element when run as written. A working index-based version must increase i inside the loop.
var values: [Int] = [2, 3, 5, 7, 11]
var index = 0
while index < values.count {
print(values[index])
index += 1
}
2
3
5
7
11
The condition index < values.count prevents the program from accessing an index beyond the array’s valid range.
Print Swift Array Elements Using forEach
The forEach method executes a closure once for every array element. It is concise when the operation consists of a simple action such as printing.
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
For more complex loop control, such as using break or continue, prefer a regular for-in loop.
Print an Entire Swift Array in One Statement
Passing an array directly to print() displays the complete collection using Swift’s array representation. This is convenient for debugging or quickly checking the array contents.
let colors = ["Red", "Green", "Blue"]
print(colors)
["Red", "Green", "Blue"]
This approach prints brackets, commas, and quotation marks as part of the array representation. Iterate over the array or use joined(separator:) when you need custom output formatting.
Print Swift Array Elements on the Same Line
The terminator parameter of print() controls what is written after each value. Set it to a space or another separator to keep the elements on the same line.
let numbers = [10, 20, 30, 40]
for number in numbers {
print(number, terminator: " ")
}
print()
10 20 30 40
The final empty print() moves subsequent output to the next line.
Print Swift String Array Elements with a Separator
For an array of strings, joined(separator:) combines all elements into one string. The specified separator is inserted between adjacent elements.
let languages = ["Swift", "Kotlin", "Java"]
print(languages.joined(separator: ", "))
Swift, Kotlin, Java
For arrays containing numbers or other non-string values, convert the elements to strings before joining them.
let scores = [78, 84, 91]
let formattedScores = scores.map(String.init).joined(separator: ", ")
print(formattedScores)
78, 84, 91
Print Swift Array Indexes and Elements Together
Use enumerated() when the output needs both the zero-based index and its corresponding element.
let fruits = ["Apple", "Banana", "Orange"]
for (index, fruit) in fruits.enumerated() {
print("Index \(index): \(fruit)")
}
Index 0: Apple
Index 1: Banana
Index 2: Orange
To display numbering beginning with 1, print index + 1 instead of index.
Print the Number of Elements in a Swift Array
The array’s count property returns its total number of elements. Printing count does not print the elements themselves.
let cities = ["Delhi", "Chennai", "Mumbai", "Kolkata"]
print("Number of elements: \(cities.count)")
Number of elements: 4
Print Elements from an Empty Swift Array Safely
Iterating over an empty array is safe. A for-in loop or forEach closure simply executes zero times. Use isEmpty when you need to print a separate message for that case.
let names: [String] = []
if names.isEmpty {
print("The array has no elements.")
} else {
for name in names {
print(name)
}
}
The array has no elements.
Print Selected Swift Array Elements with a Condition
Add an if condition inside the loop when only matching elements should be displayed.
let values = [3, 8, 11, 14, 19, 22]
for value in values {
if value.isMultiple(of: 2) {
print(value)
}
}
8
14
22
Common Errors When Printing Swift Array Elements
- Forgetting to increment a while-loop index: This creates an infinite loop that repeatedly accesses the same element.
- Using an index equal to array.count: The final valid index is
array.count - 1. Accessingarray[array.count]causes an index-out-of-range error. - Using a closed range with an empty array: A range such as
0...array.count - 1is unsafe when the array is empty. Prefer direct iteration orarray.indices. - Expecting print(array) to produce custom formatting: Direct array printing includes Swift’s brackets and separators.
- Trying to join non-string elements directly: Convert values to strings before calling
joined(separator:).
Swift Array Printing Frequently Asked Questions
How do I print all elements of an array in Swift?
Use a for-in loop and call print() for each element. For example, for item in items { print(item) }.
Can I print a complete Swift array without a loop?
Yes. Pass the array directly to print(), such as print(items). Swift displays the collection with brackets and separators.
How do I print Swift array elements on one line?
Use print(element, terminator: " ") inside a loop. For a string array, you can instead use joined(separator:).
How do I print both the index and value of a Swift array?
Iterate over array.enumerated(). It produces an index and element for every iteration.
How do I print the number of elements in a Swift array?
Print the array’s count property, such as print(array.count).
Swift Array Printing Editorial QA Checklist
- Verify that every index-based loop increments its index and stops before
array.count. - Confirm that examples intended to print each element use valid arrays and produce the displayed output.
- Check that direct array output is distinguished from custom formatted output.
- Confirm that
joined(separator:)examples operate on strings or convert elements to strings first. - Test empty-array examples to ensure they do not create invalid ranges or out-of-bounds access.
- Verify that output blocks preserve the same element order as the source array.
Summary of Printing Swift Array Elements
Use a for-in loop for straightforward array iteration, a while loop when explicit index control is required, and forEach for concise closure-based processing. Use print(array) for a quick representation of the complete array, enumerated() for indexes and values, count for the number of elements, and joined(separator:) for formatted string output.
Conclusion
In this Swift Tutorial, we have learned how to print the elements of an array with the help of Swift example programs.
TutorialKart.com