How to merge or append two arrays in Swift example
This blog solves the below problems for developers
- How to merge two arrays in swift
- Concatenate or append or combine two arrays in swift
Merging two arrays is an append either into the new array or one array into another array. Once arrays are merged, The same order appears as in the order of merge.
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
result is [11, 12, 13, 21, 22, 23]
There are multiple ways we can do merge
- using
+
or+=
operator - using the append function
- joined function
- use flatMap function
How to combine or merge multiple arrays in swift
- using
+
or+=
operator
The array has a +(_:_:)
operator that appends one of the collections with other collections.
Collections can be arrays or lists or sets.
The below code merges two arrays into a new array.
import Foundation
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
var result=array1+array2
print(result)
Another example, append one of the arrays into another.
import Foundation
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
array1+=array2
print(array1)
Above both programs produces the same output.
[11, 12, 13, 21, 22, 23]
- Array append(contentsOf:) function
The array has a append
method that appends one array to the end of another array.
Syntax:
mutating func append<S>(contentsOf newElements: S) where S : Sequence, Self.Element == S.Element
It mutates the original array.
import Foundation
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
array1.append(contentsOf: array2)
print(array1) //[11, 12, 13, 21, 22, 23]
- Use joined the function
The array has joined🔗 method that appends arrays.
Syntax:
func joined() -> FlattenSequence<Self>
It returns FlattenSequence
and converts this into an array using Array Constructor.
Here is an example
import Foundation
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
var result=Array([array1,array2].joined());
print(result)
- Using the flatMap method the array has a flatMap method that returns a result with the first parameter.
Here is an example
import Foundation
var array1 = [11, 12, 13]
var array2 = [21, 22, 23]
let result = [array1, array2].flatMap { $0 }
print(result)
How to merge two arrays without duplicates
All the above programs allow duplicates after merging multiple arrays.
This program merges two arrays by removing duplicate elements.
- Append two arrays using the + operator
- pass the result to Set, which does not allow duplicates
- convert the set to an array using the array constructor
Here is an example code
import Foundation
var array1 = [11, 12, 13,21]
var array2 = [21, 22, 23]
// Merge with duplicates
let duplicates=array1 + array2
print(duplicates)
// Merge arrays without duplicates
let result = Array(Set(array1 + array2))
print(result)
[11, 12, 13, 21, 21, 22, 23]
[11, 22, 13, 21, 12, 23]