如何在Swift中连接或合并数组?

时间:2021-09-08 09:06:35

If there are two arrays created in swift like this:

如果在swift中创建了两个数组:

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

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

它们如何被合并到[1,2,3,4,5,6]?

9 个解决方案

#1


512  

You can concatenate the arrays with +, building a new array

您可以将数组与+连接起来,构建一个新的数组。

let c = a + b
print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

or append one array to the other with += (or append):

或用+=(或追加)将一个数组附加到另一个数组:

a += b

// Or:
a.append(contentsOf: b)  // Swift 3
a.appendContentsOf(b)    // Swift 2
a.extend(b)              // Swift 1.2

print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

#2


80  

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

使用Swift 3,根据您的需要和口味,您可以选择以下五种方式中的一种来连接/合并两个数组。


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:

Swift标准库定义了一个+(_:_:)泛型操作符。+(_:_:)有以下声明:

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:

下面的代码演示了如何使用+(_:_::)泛型运算符将两个类型为[Int]的数组合并到一个新的数组中:

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:

Swift数组有一个附加(contentsOf:)方法。附录(内容如下:)有以下声明:

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:

下面的代码演示了如何使用append(contentsOf:)方法将数组附加到另一个类型为[Int]的数组中:

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:

Swift为符合序列协议(包括数组)的所有类型提供了一个flatMap(_:)方法。flatMap(_:)有以下声明:

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:

下面的代码演示了如何使用flatMap(_:)方法将两个类型为[Int]的数组合并到一个新的数组中:

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:

Swift为符合序列协议(包括数组)的所有类型提供了一个join()方法。加入()有以下声明:

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:

此外,Swift数组还有一个init(_:)初始化器。init(_:)具有以下声明:

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:

因此,下面的游戏代码演示了如何使用join()方法和init(_:)初始化器将两组类型[Int]合并到一个新的数组中:

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:

Swift数组有一个reduce(_:_:)方法。reduce(_:_:)具有以下声明:

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:

下面的操场代码展示了如何使用reduce(_:_::)方法将两个类型为[Int]的数组合并到一个新的数组中:

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]

#3


21  

If you are not a big fan of operator overloading, or just more of a functional type:

如果你不喜欢操作符重载,或者只是更喜欢功能类型:

// use flatMap
let result = [
    ["merge", "me"], 
    ["We", "shall", "unite"],
    ["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]

// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]

#4


19  

My favorite method since Swift 2.0 is flatten

自Swift 2.0以来,我最喜欢的方法是flatten

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

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

这将返回展平方向的集合,因此如果您只想要一个集合类型,这就足够了,您将免费得到延迟的评估。如果你确实需要数组,你可以这样做:

let c = Array([a, b].flatten())

#5


9  

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

为了完成可能的替代方案列表,reduce可以用于实现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...).

但是请注意,flatten没有返回一个LazyColletion,所以惰性行为不会沿着链传播到下一个操作(map, flatMap, filter,等等)。

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:

如果在您的特定情况下,lazyness是有意义的,请记住在前面或后面加一个.lazy to flatten(),例如,修改Tomasz样例:

let c = [a, b].lazy.flatten() 

#6


3  

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

如果您希望在特定索引之后插入第二个数组,您可以这样做(从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] 

#7


3  

Swift 3.0

斯威夫特3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

您可以通过与加法运算符(+)添加两个具有兼容类型的现有数组来创建一个新的数组。新数组的类型是从您添加到一起的两个数组的类型中推断出来的,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

这是上述代码的正确结果。

#8


1  

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]

#9


0  

Marge array that are different data types :

不同数据类型的Marge数组:

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]]

#1


512  

You can concatenate the arrays with +, building a new array

您可以将数组与+连接起来,构建一个新的数组。

let c = a + b
print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

or append one array to the other with += (or append):

或用+=(或追加)将一个数组附加到另一个数组:

a += b

// Or:
a.append(contentsOf: b)  // Swift 3
a.appendContentsOf(b)    // Swift 2
a.extend(b)              // Swift 1.2

print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]

#2


80  

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

使用Swift 3,根据您的需要和口味,您可以选择以下五种方式中的一种来连接/合并两个数组。


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:

Swift标准库定义了一个+(_:_:)泛型操作符。+(_:_:)有以下声明:

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:

下面的代码演示了如何使用+(_:_::)泛型运算符将两个类型为[Int]的数组合并到一个新的数组中:

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:

Swift数组有一个附加(contentsOf:)方法。附录(内容如下:)有以下声明:

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:

下面的代码演示了如何使用append(contentsOf:)方法将数组附加到另一个类型为[Int]的数组中:

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:

Swift为符合序列协议(包括数组)的所有类型提供了一个flatMap(_:)方法。flatMap(_:)有以下声明:

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:

下面的代码演示了如何使用flatMap(_:)方法将两个类型为[Int]的数组合并到一个新的数组中:

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:

Swift为符合序列协议(包括数组)的所有类型提供了一个join()方法。加入()有以下声明:

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:

此外,Swift数组还有一个init(_:)初始化器。init(_:)具有以下声明:

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:

因此,下面的游戏代码演示了如何使用join()方法和init(_:)初始化器将两组类型[Int]合并到一个新的数组中:

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:

Swift数组有一个reduce(_:_:)方法。reduce(_:_:)具有以下声明:

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:

下面的操场代码展示了如何使用reduce(_:_::)方法将两个类型为[Int]的数组合并到一个新的数组中:

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]

#3


21  

If you are not a big fan of operator overloading, or just more of a functional type:

如果你不喜欢操作符重载,或者只是更喜欢功能类型:

// use flatMap
let result = [
    ["merge", "me"], 
    ["We", "shall", "unite"],
    ["magic"]
].flatMap { $0 }
// Output: ["merge", "me", "We", "shall", "unite", "magic"]

// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]

#4


19  

My favorite method since Swift 2.0 is flatten

自Swift 2.0以来,我最喜欢的方法是flatten

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

let c = [a, b].flatten()

This will return FlattenBidirectionalCollection so if you just want a CollectionType this will be enough and you will have lazy evaluation for free. If you need exactly the Array you can do this:

这将返回展平方向的集合,因此如果您只想要一个集合类型,这就足够了,您将免费得到延迟的评估。如果你确实需要数组,你可以这样做:

let c = Array([a, b].flatten())

#5


9  

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

为了完成可能的替代方案列表,reduce可以用于实现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...).

但是请注意,flatten没有返回一个LazyColletion,所以惰性行为不会沿着链传播到下一个操作(map, flatMap, filter,等等)。

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:

如果在您的特定情况下,lazyness是有意义的,请记住在前面或后面加一个.lazy to flatten(),例如,修改Tomasz样例:

let c = [a, b].lazy.flatten() 

#6


3  

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

如果您希望在特定索引之后插入第二个数组,您可以这样做(从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] 

#7


3  

Swift 3.0

斯威夫特3.0

You can create a new array by adding together two existing arrays with compatible types with the addition operator (+). The new array's type is inferred from the type of the two array you add together,

您可以通过与加法运算符(+)添加两个具有兼容类型的现有数组来创建一个新的数组。新数组的类型是从您添加到一起的两个数组的类型中推断出来的,

let arr0 = Array(repeating: 1, count: 3) // [1, 1, 1]
let arr1 = Array(repeating: 2, count: 6)//[2, 2, 2, 2, 2, 2]
let arr2 = arr0 + arr1 //[1, 1, 1, 2, 2, 2, 2, 2, 2]

this is the right results of above codes.

这是上述代码的正确结果。

#8


1  

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]

#9


0  

Marge array that are different data types :

不同数据类型的Marge数组:

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]]