How to reverse array in Swift without using “.reverse()”?

后端 未结 21 1739
清歌不尽
清歌不尽 2020-12-08 20:14

I have array and need to reverse it without Array.reverse method, only with a for loop.

var names:[String] = [\"Apple\", \"Microsof         


        
21条回答
  •  眼角桃花
    2020-12-08 20:47

    There's also stride to generate a reversed index:

    let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversed = [String]()
    
    for index in (names.count - 1).stride(to: -1, by: -1) {
        reversed.append(names[index])
    }
    

    It also works well with map:

    let reversed = (names.count - 1).stride(to: -1, by: -1).map { names[$0] }
    

    Note: stride starts its index at 1, not at 0, contrary to other Swift sequences.

    However, to anyone reading this in the future: use .reverse() instead to actually reverse an array, it's the intended way.

提交回复
热议问题