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

后端 未结 21 1597
清歌不尽
清歌不尽 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:58
    var rArray : [Int] = [2,5,6,8,3,8,9,10]
    var ReArray = [Int]()
    var a : Int = 1
    
    func reversed (_ array: [Int]) -> [Int] {
        for i in array {
            ReArray.append(array[array.count-a])
            a += 1
        }
    
        rArray = ReArray
    
        return rArray
    }
    
    reversed(rArray)
    
    print(rArray)
    
    0 讨论(0)
  • 2020-12-08 21:00

    Here you go:

    var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversedNames = [String]()
    
    for var arrayIndex = names.count - 1 ; arrayIndex >= 0 ; arrayIndex-- {
        reversedNames.append(names[arrayIndex])
    }
    
    0 讨论(0)
  • 2020-12-08 21:02

    This will work with any sized array.

    import Cocoa
    
    var names:[String] = [ "A", "B", "C", "D", "E","F"]
    var c = names.count - 1
    for i in 0...(c/2-1) { swap(&names[i],&names[c-i]) }
    
    print(names)
    
    0 讨论(0)
  • 2020-12-08 21:04
    // Swap the first index with the last index.
    // [1, 2, 3, 4, 5] -> pointer on one = array[0] and two = array.count - 1
    // After first swap+loop increase the pointer one and decrease pointer two until
    // conditional is not true. 
    
    func reverseInteger(array: [Int]) -> [Int]{
            var array = array
            var first = 0
            var last = array.count - 1
            while first < last {
                array.swapAt(first, last)
                first += 1
                last -= 1
            }
            return array
        }
    
    input-> [1, 2, 3, 4, 5] return->[5, 4, 3, 2, 1]
    
    0 讨论(0)
  • 2020-12-08 21:06

    Ignoring checks for emptiness..

    var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversedNames: [String]
    reversedNames = []
    
    for name in names {
        reversedNames.insert((name), atIndex:0)
    }
    
    0 讨论(0)
  • 2020-12-08 21:08

    Do you really need a for loop? If not, you can use reduce.

    I guess that this is the shortest way to achieve it without reversed() method (Swift 3.0.1):

    ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"].reduce([],{ [$1] + $0 })
    
    0 讨论(0)
提交回复
热议问题