且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将swift中的嵌套数组转换为一维数组

更新时间:2022-11-22 18:00:57

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