How can I flatten an array swiftily in Swift?

前端 未结 3 1363
说谎
说谎 2021-01-17 10:23

I want to turn this:

let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

into this:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

ver

3条回答
  •  不要未来只要你来
    2021-01-17 11:02

    Flatten function in Array :

    let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    let y = Array(x.flatten())
    print(y)
    

    flatMap function in Array :

    let x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    let y = x.flatMap({$0})
    print(y)
    

    Your Output :

    For more : Array in Swift

提交回复
热议问题