Concatenate/Merge Two Arrays into One Array in Swift 4 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

16 Oct 2017

Concatenate/Merge Two Arrays into One Array in Swift 4

Append two arrays into a new array with Swift standard library's.

There are 5 different ways for merging arrays in swift. We may choose one of the five following ways according to your needs and requirements.

Sorting Arrays in Swift

Concatenate/Merge Two Arrays into One Array in Swift 4

1. +(_:_:) generic operator:

The following piece of code shows how to merge two arrays of type [Int] into a new array using +(_:_:) generic operator:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = arr1 + arr2
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'


2. append(contentsOf:):

The following piece of code shows how to append two arrays of type [Int] into a new array using append(contentsOf:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
arr1.append(contentsOf: arr2)
print(arr1)
// output will be '[1, 2, 3, 4, 5, 6]'


3. flatMap(_:):

The following piece of code shows how to concatenate two arrays of type [Int] into a new array using flatMap(_:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = [arr1, arr2].flatMap({ (element: [Int]) -> [Int] in
    return element
})
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

4. joined():

Swift provides a joined() method for all types that conform to Sequence protocol (including Array).

So, following piece of code shows how to join two arrays of type [Int] into a new array using Sequence's joined() method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let flattenCollection = [arr1, arr2].joined()
let finalArray = Array(flattenCollection)
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

5. reduce(_:_:):

The following piece of code shows how to merge two arrays of type [Int] into a new array using reduce(_:_:) method:

var arr1 = [1, 2, 3]
let arr2 = [4, 5, 6]
let finalArray = [arr1, arr2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
    return result + element
})
print(finalArray)
// output will be '[1, 2, 3, 4, 5, 6]'

Use any one of above methods based on your requirement.

No comments:

Post a Comment

Post Top Ad