- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I concatenate or Merge Arrays in Swift?
Swift provides us with two different ways to concatenate or merge arrays in the Swift language.
You can use the + (plus) operator or the append() method. You will see other methods also of how you can merge multiple arrays in Swift. These methods are −
Using plus (+) operator
Using append(contentOf:) method
Using flatMap() high-order function
Using joined() method
Using reduce() high-order function
Method 1: Merge Arrays Using The + Operator
Syntax
let outputArray = firstArray + secondArray
In order to use + operator to merge the arrays, simply it works as a binary operator that returns a newly merged array.
Algorithm
Step 1 − Declare arrays
Step 2 − Merge both arrays using the + operator
Step 3 − Store the new merged array in another variable
Example
import Foundation let firstArray: [String] = ["1", "2", "3", "4", "5"] let secondArray: [String] = ["6", "7", "8", "9", "10"] let outputArray = firstArray + secondArray print("Array 1 = ",firstArray,"\nArray 2 = ",secondArray,"\nMerged Array =", outputArray)
Output
Array 1 = ["1", "2", "3", "4", "5"] Array 2 = ["6", "7", "8", "9", "10"] Merged Array ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
Note that the + (plus) operator returns a newly created array that is the result of concatenation.
Example
Remember that the + (plus) operator takes care of type safety. It means you cannot perform this operator on two different types of arrays. If you do that, the compiler will give you an error like the one below −
import Foundation let firstArray: [String] = ["1", "2", "3", "4", "5"] let secondArray: [Int] = [6, 7, 8, 9, 10] let outputArray = firstArray + secondArray print(outputArray)
Output
Error
main.swift:4:30: error: binary operator '+' cannot be applied to operands of type '[String]' and '[Int]' let outputArray = firstArray + secondArray
In the above example, you are trying to merge the strings' array and the integers' array which is not allowed.
Example
Merge more than two arrays −
In the following example we are going to merge 3 arrays in one array and print the output −
import Foundation let firstArray: [Int] = [1, 2, 3] let secondArray: [Int] = [4, 5, 6] let thirdArray: [Int] = [7, 8, 9] let mergedArray = firstArray + secondArray + thirdArray print(mergedArray)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2: Merge Arrays Using The Append(contentsOf:) Method
Syntax
firstArray.append(contentsOf: secondArray)
In order to append the content of an array, you have to call the append(contentsOf:) method with the target array.
Algorithm
Before moving to an example, you should note that this method does not return any new array. It appends the content of the target array to the caller array.
Example
import Foundation var firstArray: [String] = ["1", "2", "3", "4", "5"] let secondArray: [String] = ["6", "7", "8", "9", "10"] firstArray.append(contentsOf: secondArray) print(firstArray)
Output
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
You can see that firstArray is a variable (not a constant) to append the content of secondArray.
Example
You can also use the += operator to concatenate arrays, which is equivalent to calling the append(contentsOf:) method like below −
import Foundation var firstArray: [String] = ["1", "2", "3", "4", "5"] let secondArray: [String] = ["6", "7", "8", "9", "10"] firstArray += secondArray
Example
Merge more than two arrays −
import Foundation var firstArray: [Int] = [1, 2, 3] let secondArray: [Int] = [4, 5, 6] let thirdArray: [Int] = [7, 8, 9] firstArray.append(contentsOf: secondArray) firstArray.append(contentsOf: thirdArray) print(firstArray)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 3: Merge Arrays Using FlatMap()
Syntax
In Swift, flatMap is a method on Sequence that transforms each element of the sequence by applying a transformation function and flattening the resulting sequence into a single sequence. The transformation function can return an optional value, and the method will automatically discard nil values.
let mergedArray = [firstArray, secondArray, thirdArray].flatMap({ $0 })
In order to use the flatMap() function, you need to pass an array of the combined array which results in the new merged array.
Algorithm
Here is an example of how flatMap can be used to merge multiple arrays −
Step 1 − Initialize your arrays
Step 2 − Combine all the arrays into one array
Step 3 − Call the flatMap() function on the combined array.
Step 4 − Store the resulting array in a new variable.
Example
import Foundation let firstArray: [Int] = [1, 2, 3] let secondArray: [Int] = [4, 5, 6] let thirdArray: [Int] = [7, 8, 9] let mergedArray = [firstArray, secondArray, thirdArray].flatMap({ $0 }) print(mergedArray)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 4: Merge Arrays Using joined()
Syntax
let flattenCollection = [firstArray, secondArray, thirdArray].joined() let mergedArray = Array(flattenCollection)
You can call the join function on a combined array which results in the elements being into a flat collection.
Now, you need to create a new array from a flat array to get all the elements into a single array.
Algorithm
Step 1 − Initialize your arrays
Step 2 − Join them using the joined() function
Step 3 − Store the result from the joined function
Step 4 − Convert the joined array using Array() into a single array
Example
This method returns the elements of this sequence of sequences, concatenated. For example,
import Foundation let firstArray: [Int] = [1, 2, 3] let secondArray: [Int] = [4, 5, 6] let thirdArray: [Int] = [7, 8, 9] let flattenCollection = [firstArray, secondArray, thirdArray].joined() let mergedArray = Array(flattenCollection) print(mergedArray)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 5: Merge Arrays Using reduce()
Syntax
This method returns the result of combining the elements of the sequence using the given closure.
let flattenArray = [firstArray, secondArray, thirdArray].reduce([]) { partialResult, element in partialResult + element }
Basically, you have to pass combined arrays with reduce() function. In order to use the reduce() function, you need to assign an initial result which is the initialization of the result.
Algorithm
Step 1 − Initialise your arrays
Step 2 − Combine all the arrays into a single array
Step 3 − Assign the initial result
Step 4 − Merge each element into a partial result
Example
In this code, we are going to merge 3 arrays using reduce() function.
import Foundation let firstArray: [Int] = [1, 2, 3] let secondArray: [Int] = [4, 5, 6] let thirdArray: [Int] = [7, 8, 9] let flattenArray = [firstArray, secondArray, thirdArray].reduce([]) { partialResult, element in partialResult + element } print(flattenArray)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Conclusion
You learned about different methods to merge arrays in Swift. Each method can be used for a different purpose in different scenarios.