How do I concatenate or merge arrays in Swift?

2019-01-03 12:28发布

If there are two arrays created in swift like this:

var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]

How can they be merged to [1, 2, 3, 4, 5, 6]?

11条回答
虎瘦雄心在
2楼-- · 2019-01-03 12:35

Marge array that are different data types :

var arrayInt = [Int]()
arrayInt.append(6)
var testArray = ["a",true,3,"b"] as [Any]
testArray.append(someInt)

Output :

["a", true, 3, "b", "hi", 3, [6]]
查看更多
该账号已被封号
3楼-- · 2019-01-03 12:37

With Swift 3, according to your needs and tastes, you may choose one of the five following ways to concatenate/merge two arrays.


1. Merge two arrays into a new array with Swift standard library's +(_:_:) generic operator

Swift standard library defines a +(_:_:) generic operator. +(_:_:) has the following declaration:

func +<RRC1 : RangeReplaceableCollection, RRC2 : RangeReplaceableCollection where RRC1.Iterator.Element == RRC2.Iterator.Element>(lhs: RRC1, rhs: RRC2) -> RRC1

Creates a new collection by concatenating the elements of two collections.

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

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = array1 + array2
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

2. Append an array to another array with Array's append(contentsOf:) method

Swift Array has an append(contentsOf:) method. append(contentsOf:) has the following declaration:

public mutating func append<S>(contentsOf newElements: S) where S : Sequence, S.Iterator.Element == Element)

Adds the elements of a sequence or collection to the end of this collection.

The following Playground code shows how to append an array to another array of type [Int] using append(contentsOf:) method:

var array1 = [1, 2, 3]
let array2 = [4, 5, 6]

array1.append(contentsOf: array2)
print(array1) // prints [1, 2, 3, 4, 5, 6]

3. Merge two arrays into a new array with Sequence's flatMap(_:) method

Swift provides a flatMap(_:) method for all types that conform to Sequence protocol (including Array). flatMap(_:) has the following declaration:

func flatMap<SegmentOfResult : Sequence>(_ transform: (Self.Iterator.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element]

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

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

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].flatMap({ (element: [Int]) -> [Int] in
    return element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

4. Merge two arrays into a new array with Sequence's joined() method and Array's init(_:) initializer

Swift provides a joined() method for all types that conform to Sequence protocol (including Array). joined() has the following declaration:

func joined() -> FlattenSequence<Self>

Returns the elements of this sequence of sequences, concatenated.

Besides, Swift Array has a init(_:) initializer. init(_:) has the following declaration:

init<S : Sequence where S.Iterator.Element == Element>(_ s: S)

Creates an array containing the elements of a sequence.

Therefore, the following Playground code shows how to merge two arrays of type [Int] into a new array using joined() method and init(_:) initializer:

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenCollection = [array1, array2].joined() // type: FlattenBidirectionalCollection<[Array<Int>]>
let flattenArray = Array(flattenCollection)
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]

5. Merge two arrays into a new array with Array's reduce(_:_:) method

Swift Array has a reduce(_:_:) method. reduce(_:_:) has the following declaration:

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

Returns the result of calling the given combining closure with each element of this sequence and an accumulating value.

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

let array1 = [1, 2, 3]
let array2 = [4, 5, 6]

let flattenArray = [array1, array2].reduce([], { (result: [Int], element: [Int]) -> [Int] in
    return result + element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6]
查看更多
甜甜的少女心
4楼-- · 2019-01-03 12:41

Here's the shortest way to merge two arrays.

 var array1 = [1,2,3]
 let array2 = [4,5,6]

Concatenate/merge them

array1 += array2
New value of array1 is [1,2,3,4,5,6]
查看更多
趁早两清
5楼-- · 2019-01-03 12:48

To complete the list of possible alternatives, reduce could be used to implement the behavior of flatten:

var a = ["a", "b", "c"] 
var b = ["d", "e", "f"]

let res = [a, b].reduce([],combine:+)

The best alternative (performance/memory-wise) among the ones presented is simply flatten, that just wrap the original arrays lazily without creating a new array structure.

But notice that flatten does not return a LazyColletion, so that lazy behavior will not be propagated to the next operation along the chain (map, flatMap, filter, etc...).

If lazyness makes sense in your particular case, just remember to prepend or append a .lazy to flatten(), for example, modifying Tomasz sample this way:

let c = [a, b].lazy.flatten() 
查看更多
聊天终结者
6楼-- · 2019-01-03 12:48
var arrayOne = [1,2,3]
var arrayTwo = [4,5,6]

if you want result as : [1,2,3,[4,5,6]]

arrayOne.append(arrayTwo)

above code will convert arrayOne as a single element and add it to the end of arrayTwo.

if you want result as : [1, 2, 3, 4, 5, 6] then,

arrayOne.append(contentsOf: arrayTwo)

above code will add all the elements of arrayOne at the end of arrayTwo.

Thanks.

查看更多
Deceive 欺骗
7楼-- · 2019-01-03 12:52

If you want the second array to be inserted after a particular index you can do this (as of Swift 2.2):

let index = 1
if 0 ... a.count ~= index {
     a[index..<index] = b[0..<b.count]
}
print(a) // [1.0, 4.0, 5.0, 6.0, 2.0, 3.0] 
查看更多
登录 后发表回答