在 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) // prints [1, 2, 3, 4, 5, 6, 7, 8, 9]