在 Swift 5 中,你可以选择以下三种方式之一来展开数组。
#1. 使用 Array
的 flatMap(_:)
方法来展开数组
在 Swift 中,符合 Sequence
协议(包括 Array
)的类型都有一个 flatMap(_:)
方法。 Array
的 flatMap(_:)
声明如下:
func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence
返回一个数组,该数组是将给定的转换函数对此序列的每个元素调用后所得结果串联而成。
以下 Playground 示例代码显示了如何使用 flatMap(_:)
将类型为 [[Int]]
的 Array
扁平化为类型为 [Int]
的数组:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flattenArray = array.flatMap({ (element: [Int]) -> [Int] in
return element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6, 7, 8, 9]
#2. 使用Array
的joined()
方法将数组扁平化
Array
有一个名为joined()
的方法。 joined()
的声明如下:
func joined() -> FlattenSequence<Array<Element>>
返回这个序列中所有子序列的元素,拼接在一起。
以下 Playground 示例代码演示了如何使用 joined()
将类型为 [[Int]]
的 Array
扁平化为类型为 [Int]
:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flattenCollection = array.joined()
let flattenArray = Array(flattenCollection)
print(flattenArray) // prints [1, 2, 3, 4, 5, 6, 7, 8, 9]
#3. 使用Array
的reduce(_:_:)
方法展开一个数组
Swift Array
提供了一个reduce(_:_:)
方法,其声明如下:
func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
使用给定的闭包组合序列的元素,并返回结果。
以下Playground示例代码展示了如何使用reduce(_:_:)
将类型为[[Int]]
的Array
扁平化为类型为[Int]
:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flattenArray = array.reduce([], { (result: [Int], element: [Int]) -> [Int] in
return result + element
})
print(flattenArray) // prints [1, 2, 3, 4, 5, 6, 7, 8, 9]
作为
reduce(_:_:)
的替代方案,您可以使用
reduce(into:_:)
:
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let flattenArray = array.reduce(into: [Int]()) { (result: inout [Int], element: [Int]) in
result += element
}
print(flattenArray)