将swift中的嵌套数组转换为一维数组 [英] Convert nested array in swift to single dimensional array

查看:31
本文介绍了将swift中的嵌套数组转换为一维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于 [[[ ]]] 的结构,我想将其转换为 [].

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)
}

这篇关于将swift中的嵌套数组转换为一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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