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

后端 未结 21 1751
清歌不尽
清歌不尽 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 21:08

    do you mean

    var names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    var newNames = [String]()
    
    for var i = names.count - 1; i >= 0 ; i-- {
      newNames.append(names[i])
    }
    names = newNames
    

    or

    names.map {newNames.insert($0, atIndex: 0)}
    names = newNames
    

提交回复
热议问题