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

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

    Here is how I did it and there is no warning for Swift 3

    let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    var reversedNames = [String]()
    
    for name in names.enumerate() {
      let newIndex = names.count - 1 - name.index
      reversedNames.append(names[newIndex])
    }
    

    or just simply

    reversedNames = names.reverse()
    

提交回复
热议问题