Convert nested array in swift to single dimensional array

后端 未结 4 1725
谎友^
谎友^ 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:28

    This is exactly what flatMap() does:

    let arr = [ [ [ "A", "B" ], ["C"] ], [ [ "D", "E" ], ["F"] ] ]
    
    // each call reduces the array by one dimension
    
    let flattened = arr.flatMap{$0}.flatMap{$0}
    
    // returns ["A", "B", "C", "D", "E", "F"]
    

提交回复
热议问题