在 Swift 中展平数组 [英] Flatten an Array of Arrays in Swift

查看:33
本文介绍了在 Swift 中展平数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中是否有对应的 flatten 在 Scala、Xtend、Groovy、Ruby 和 co 中?

Is there a counterpart in Swift to flatten in Scala, Xtend, Groovy, Ruby and co?

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,但那有点糟糕

of course i could use reduce for that but that kinda sucks

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

推荐答案

Swift >= 3.0

Swift >= 3.0

减少:

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 }

加入:

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

这篇关于在 Swift 中展平数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆