Swift – Append/Concatenate Arrays
In Swift, you can concatenate arrays with the + operator, append another array to an existing variable with +=, or add a sequence of elements with append(contentsOf:). The appropriate method depends on whether you need a new array or want to modify an existing one.
Swift Array Concatenation Syntax Using the + Operator
To append or concatenate two arrays in Swift, use plus + operator with the two arrays as operands.
Following is a quick example to append an array at the end of another array.
var new_array = array_1 + array_2
You have to remember that the elements of array_2 are appended to that of array_1 in the new array.
The + operator returns a new array. It does not change either source array. Both operands must contain compatible element types.
Example 1 – Append two Integer Arrays in Swift
In this example Swift program, we will append or concatenate two integer arrays.
main.swift
var array1:[Int] = [22, 54]
var array2:[Int] = [35, 68]
var new_array = array1 + array2
for str in new_array {
print( "\(str)" )
}
Output
22
54
35
68
The resulting array preserves the order of both inputs: all elements from array1 appear first, followed by all elements from array2.
Example 2 – Append two String Arrays in Swift
In this example program, we will append or concatenate two string arrays.
main.swift
var array1:[String] = ["TutorialKart","Swift Tutorial"]
var array2:[String] = ["iOS Tutorial","Best Tutorials"]
var new_array = array1 + array2
for str in new_array {
print( "\(str)" )
}
Output
TutorialKart
Swift Tutorial
iOS Tutorial
Best Tutorials
Append One Swift Array In Place with +=
Use += when the destination is a variable and you want to add all elements from another array to it. Unlike +, this changes the destination array.
var numbers = [10, 20]
let moreNumbers = [30, 40]
numbers += moreNumbers
print(numbers)
Output
[10, 20, 30, 40]
The destination must be declared with var. A constant declared with let cannot be changed with +=.
Append Array Elements with append(contentsOf:)
The append(contentsOf:) method adds every element from another array or compatible sequence to the end of a mutable array. This method clearly communicates that the existing array is being changed.
var queue = ["A", "B"]
let nextItems = ["C", "D"]
queue.append(contentsOf: nextItems)
print(queue)
Output
["A", "B", "C", "D"]
Swift also accepts other sequences whose elements match the destination element type. For example, an integer range can be appended to an integer array.
var values = [1, 2]
values.append(contentsOf: 3...5)
print(values)
Output
[1, 2, 3, 4, 5]
Choose Between +, +=, and append(contentsOf:)
| Swift array operation | Result | Use it when |
|---|---|---|
array1 + array2 | Creates a new array | You want to keep both input arrays unchanged |
array1 += array2 | Changes array1 | You want concise in-place concatenation |
array1.append(contentsOf: array2) | Changes array1 | You want an explicit method call or are appending another sequence |
For a one-time result, + is usually the clearest choice. For repeated additions to the same mutable array, += or append(contentsOf:) avoids repeatedly assigning a separate result variable.
Merge Two Swift Arrays Without Duplicate Elements
Concatenation does not remove duplicates. To merge two arrays while preserving the first occurrence of each value, combine them and filter with a Set. The element type must conform to Hashable.
let first = [1, 2, 3]
let second = [3, 4, 2, 5]
var seen = Set<Int>()
let merged = (first + second).filter {
seen.insert($0).inserted
}
print(merged)
Output
[1, 2, 3, 4, 5]
Creating Array(Set(first + second)) is shorter, but a set does not provide the same first-occurrence ordering behavior as the filtering approach above.
Flatten an Array of Arrays with joined()
When the source is a nested array such as [[Int]], use joined() and create an Array from the flattened sequence.
let groups = [[1, 2], [3, 4], [5]]
let flattened = Array(groups.joined())
print(flattened)
Output
[1, 2, 3, 4, 5]
Do not confuse this operation with joined(separator:) on a sequence of strings. That method builds one String with a separator; it does not merge two ordinary arrays into another array.
Concatenate Swift Arrays with Different Numeric Types
Swift arrays are strongly typed, so an [Int] array cannot be concatenated directly with a [Double] array. Convert one array to a common element type before combining them.
let integers = [1, 2]
let decimals = [3.5, 4.5]
let combined = integers.map(Double.init) + decimals
print(combined)
Output
[1.0, 2.0, 3.5, 4.5]
Swift Array Concatenation Checks
- Confirm that both arrays use the same or compatible element type.
- Use
+when the original arrays must remain unchanged. - Declare the destination with
varbefore using+=orappend(contentsOf:). - Check whether duplicate values should be retained or removed.
- Use
Array(nestedArrays.joined())only when flattening a collection of collections.
Swift Array Concatenation FAQs
Does the + operator modify the original Swift arrays?
No. The + operator creates and returns a new array. The two source arrays remain unchanged.
Can Swift concatenate arrays containing different element types?
Not directly. Both arrays need a compatible element type. Convert the elements to a shared type before concatenating them.
Should I use += or append(contentsOf:) to append an array?
Both mutate a variable array by adding multiple elements. Use += for concise operator syntax or append(contentsOf:) when an explicit method call is clearer.
How do I merge Swift arrays without duplicates?
Combine the arrays and filter the result with a Set that records values already encountered. This preserves the first occurrence when the element type conforms to Hashable.
Swift Array Concatenation Summary
In this Swift Tutorial, we have learned to append or concatenate two arrays in Swift programming. Use + to create a new combined array, and use += or append(contentsOf:) to modify an existing array. For nested arrays, use joined(), and apply an order-preserving filter when duplicate elements must be removed.
TutorialKart.com