ios 如何在 Swift 中连接或合并数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25146382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I concatenate or merge arrays in Swift?
提问by Hristo
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]
?
回答by Martin R
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
):
或使用+=
(或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]
回答by Imanou Petit
With Swift 5, according to your needs, you may choose one of the six following waysto concatenate/merge two arrays.
使用 Swift 5,您可以根据需要选择以下六种方式之一来连接/合并两个数组。
#1. Merge two arrays into a new array with Array
's +(_:_:)
generic operator
#1. 使用Array
的+(_:_:)
泛型运算符将两个数组合并为一个新数组
Array
has a +(_:_:)
generic operator. +(_:_:)
has the following declaration:
Array
有一个+(_:_:)
泛型运算符。+(_:_:)
有以下声明:
Creates a new collection by concatenating the elements of a collection and a sequence.
通过连接一个集合的元素和一个序列来创建一个新的集合。
static func + <Other>(lhs: Array<Element>, rhs: Other) -> Array<Element> where Other : Sequence, Self.Element == Other.Element
The following Playground sample code shows how to merge two arrays of type [Int]
into a new array using +(_:_:)
generic operator:
以下 Playground 示例代码展示了如何[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 the elements of an array into an existing array with Array
's +=(_:_:)
generic operator
#2. 使用Array
的+=(_:_:)
泛型运算符将数组元素附加到现有数组中
Array
has a +=(_:_:)
generic operator. +=(_:_:)
has the following declaration:
Array
有一个+=(_:_:)
泛型运算符。+=(_:_:)
有以下声明:
Appends the elements of a sequence to a range-replaceable collection.
将序列的元素附加到范围可替换的集合中。
static func += <Other>(lhs: inout Array<Element>, rhs: Other) where Other : Sequence, Self.Element == Other.Element
The following Playground sample code shows how to append the elements of an array of type [Int]
into an existing array using +=(_:_:)
generic operator:
以下 Playground 示例代码显示了如何[Int]
使用+=(_:_:)
泛型运算符将类型数组的元素附加到现有数组中:
var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1 += array2
print(array1) // prints [1, 2, 3, 4, 5, 6]
#3. Append an array to another array with Array
's append(contentsOf:)
method
#3. 使用Array
'sappend(contentsOf:)
方法将一个数组附加到另一个数组
Swift Array
has an append(contentsOf:)
method. append(contentsOf:)
has the following declaration:
SwiftArray
有一个append(contentsOf:)
方法。append(contentsOf:)
有以下声明:
Adds the elements of a sequence or collection to the end of this collection.
将序列或集合的元素添加到此集合的末尾。
mutating func append<S>(contentsOf newElements: S) where S : Sequence, Self.Element == S.Element
The following Playground sample code shows how to append an array to another array of type [Int]
using append(contentsOf:)
method:
以下 Playground 示例代码显示了如何[Int]
使用append(contentsOf:)
方法将数组附加到另一个类型的数组:
var array1 = [1, 2, 3]
let array2 = [4, 5, 6]
array1.append(contentsOf: array2)
print(array1) // prints [1, 2, 3, 4, 5, 6]
#4. Merge two arrays into a new array with Sequence
's flatMap(_:)
method
#4. 使用Sequence
'sflatMap(_:)
方法将两个数组合并为一个新数组
Swift provides a flatMap(_:)
method for all types that conform to Sequence
protocol (including Array
). flatMap(_:)
has the following declaration:
SwiftflatMap(_:)
为所有符合Sequence
协议的类型(包括Array
)提供了方法。flatMap(_:)
有以下声明:
Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.
返回一个数组,其中包含使用此序列的每个元素调用给定转换的连接结果。
func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
The following Playground sample code shows how to merge two arrays of type [Int]
into a new array using flatMap(_:)
method:
以下 Playground 示例代码显示了如何[Int]
使用flatMap(_:)
方法将两个类型的数组合并为一个新数组:
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]
#5. Merge two arrays into a new array with Sequence
's joined()
method and Array
's init(_:)
initializer
#5. 使用Sequence
'sjoined()
方法和Array
'sinit(_:)
初始化程序将两个数组合并为一个新数组
Swift provides a joined()
method for all types that conform to Sequence
protocol (including Array
). joined()
has the following declaration:
Swiftjoined()
为所有符合Sequence
协议的类型(包括Array
)提供了方法。joined()
有以下声明:
Returns the elements of this sequence of sequences, concatenated.
返回此序列序列的元素,串联。
func joined() -> FlattenSequence<Self>
Besides, Swift Array
has a init(_:)
initializer. init(_:)
has the following declaration:
此外,SwiftArray
有一个init(_:)
初始化程序。init(_:)
有以下声明:
Creates an array containing the elements of a sequence.
创建一个包含序列元素的数组。
init<S>(_ s: S) where Element == S.Element, S : Sequence
Therefore, the following Playground sample code shows how to merge two arrays of type [Int]
into a new array using joined()
method and init(_:)
initializer:
因此,以下 Playground 示例代码显示了如何[Int]
使用joined()
方法和init(_:)
初始化程序将两个类型的数组合并为一个新数组:
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]
#6. Merge two arrays into a new array with Array
's reduce(_:_:)
method
#6. 使用Array
'sreduce(_:_:)
方法将两个数组合并为一个新数组
Swift Array
has a reduce(_:_:)
method. reduce(_:_:)
has the following declaration:
SwiftArray
有一个reduce(_:_:)
方法。reduce(_:_:)
有以下声明:
Returns the result of combining the elements of the sequence using the given closure.
返回使用给定闭包组合序列元素的结果。
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
The following Playground code shows how to merge two arrays of type [Int]
into a new array using reduce(_:_:)
method:
以下 Playground 代码显示了如何[Int]
使用reduce(_:_:)
方法将两个类型的数组合并为一个新数组:
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]
回答by Mazyod
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 { var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]
let c = [a, b].flatten()
}
// Output: ["merge", "me", "We", "shall", "unite", "magic"]
// ... or reduce
[[1],[2],[3]].reduce([], +)
// Output: [1, 2, 3]
回答by Tomasz B?k
My favorite method since Swift 2.0 is flatten
自 Swift 2.0 以来我最喜欢的方法是扁平化
let c = Array([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:
这将返回,FlattenBidirectionalCollection
因此如果您只想要一个CollectionType
就足够了,并且您将免费获得懒惰的评估。如果您需要确切的数组,您可以这样做:
var a = ["a", "b", "c"]
var b = ["d", "e", "f"]
let res = [a, b].reduce([],combine:+)
回答by Umberto Raimondi
To complete the list of possible alternatives, reduce
could be used to implement the behavior of flatten:
要完成可能的替代方案列表,reduce
可用于实现flatten的行为:
let c = [a, b].lazy.flatten()
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.
所提供的最佳替代方案(性能/内存方面)很简单flatten
,它只是懒惰地包装原始数组而不创建新的数组结构。
But notice that flattendoes not returna LazyCollection
, so that lazy behavior will not be propagated to the next operation along the chain (map, flatMap, filter, etc...).
但是请注意,flatten不会返回a LazyCollection
,因此惰性行为不会传播到链中的下一个操作(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:
如果懒惰在您的特定情况下有意义,请记住在 之前或附加 a.lazy
到flatten()
,例如,以这种方式修改 Tomasz 示例:
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]
回答by Vitalii
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 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]
回答by Lorem Ipsum Dolor
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,
您可以通过使用加法运算符 ( +
)将具有兼容类型的两个现有数组相加来创建新数组。新数组的类型是从你相加的两个数组的类型中推断出来的,
var arrayOne = [1,2,3]
var arrayTwo = [4,5,6]
this is the right results of above codes.
这是上述代码的正确结果。
回答by meMadhav
arrayOne.append(arrayTwo)
if you want result as : [1,2,3,[4,5,6]]
如果你想要结果为:[1,2,3,[4,5,6]]
arrayOne.append(contentsOf: arrayTwo)
above code will convert arrayOne as a single element and add it to the end of arrayTwo.
上面的代码将 arrayOne 转换为单个元素并将其添加到 arrayTwo 的末尾。
if you want result as : [1, 2, 3, 4, 5, 6] then,
如果你想要结果为:[1, 2, 3, 4, 5, 6] 那么,
var Array1 = ["Item 1", "Item 2"]
var Array2 = ["Thing 1", "Thing 2"]
var Array3 = Array1 + Array2
// Array 3 will just be them combined :)
above code will add all the elements of arrayOne at the end of arrayTwo.
上面的代码会在arrayTwo的末尾添加arrayOne的所有元素。
Thanks.
谢谢。
回答by Stotch
Swift 4.X
斯威夫特 4.X
easiest way I know is to just use the + sign
我知道的最简单的方法就是使用 + 号
var array1 = [1,2,3]
let array2 = [4,5,6]
回答by handiansom
Here's the shortest way to merge two arrays.
这是合并两个数组的最短方法。
array1 += array2
New value of array1 is [1,2,3,4,5,6]
Concatenate/merge them
连接/合并它们
##代码##