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

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

    Here is @Abhinav 's answer translated to Swift 2.2 :

    var names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversedNames = [String]()
    
    for arrayIndex in (names.count - 1).stride(through: 0, by: -1) {
        reversedNames.append(names[arrayIndex])
    }
    

    Using this code shouldn't give you any errors or warnings about the use deprecated of C-style for-loops or the use of --.

    Swift 3 - Current:

    let names: [String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversedNames = [String]()
    
    for arrayIndex in stride(from: names.count - 1, through: 0, by: -1) {
        reversedNames.append(names[arrayIndex])
    }
    

    Alternatively, you could loop through normally and subtract each time:

    let names = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    let totalIndices = names.count - 1 // We get this value one time instead of once per iteration.
    
    var reversedNames = [String]()
    
    for arrayIndex in 0...totalIndices {
        reversedNames.append(names[totalIndices - arrayIndex])
    }
    

提交回复
热议问题