Convert nested array in swift to single dimensional array

后端 未结 4 1723
谎友^
谎友^ 2021-01-29 12:59

I have a structure like [[[ ]]] which I want to convert to [].

E.g. [ [ [ \"Hi\" ] ] ] into [ \"Hi\" ]

How

4条回答
  •  星月不相逢
    2021-01-29 13:11

    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"]
    

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

提交回复
热议问题