快速将嵌套数组转换为一维数组 [英] Convert nested array in swift to single dimensional array
本文介绍了快速将嵌套数组转换为一维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似[[[ ]]]
的结构,我想将其转换为[]
.
I have a structure like [[[ ]]]
which I want to convert to []
.
例如[ [ [ "Hi" ] ] ]
转换为[ "Hi" ]
如何在Swift中执行此操作?
How can I do this in Swift?
推荐答案
joined()
返回(串联的)集合元素(的懒惰视图).可以重复应用
更深层的嵌套集合:
joined()
returns (a lazy view of) the elements of an collection, concatenated. This can be applied repeatedly for
deeper nested collections:
let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]
let flattened = Array(arr.joined().joined())
print(flattened) // ["A", "B", "C", "D", "E", "F"]
外部Array()
构造函数根据序列构建数组.
除此之外,不会创建任何中间数组.
The outer Array()
constructor builds an array from the sequence.
Apart from that, no intermediate arrays are created.
如果只想遍历嵌套数组,则联接 顺序就足够了:
If you just want to iterate over the nested array then the joined sequence is sufficient:
for elem in arr.joined().joined() {
print(elem)
}
这篇关于快速将嵌套数组转换为一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文