小编典典

在 Swift 中展平一个数组

all

Swift 中是否有对应的flattenScala、Xtend、Groovy、Ruby 等?

var aofa = [[1,2,3],[4],[5,6,7,8,9]]
aofa.flatten() // shall deliver [1,2,3,4,5,6,7,8,9]

当然我可以为此使用 reduce 但这有点糟糕

var flattened = aofa.reduce(Int[]()){
    a,i in var b : Int[] = a
    b.extend(i)
    return b
}

阅读 89

收藏
2022-07-12

共1个答案

小编典典

斯威夫特 >= 3.0

reduce

let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let reduced = numbers.reduce([], +)

flatMap

let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let flattened = numbers.flatMap { $0 }

joined

let numbers = [[1,2,3],[4],[5,6,7,8,9]]
let joined = Array(numbers.joined())

在此处输入图像描述

2022-07-12