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

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

    I like simple codes.

    var names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]

    var reversedNames = [""]
    
    for name in names {
        reversedNames.insert(name, at: 0)
    }
    
    print(reversedNames)
    
    0 讨论(0)
  • 2020-12-08 20:55

    Here is the most simpler way.

    let names:[String] = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
    
    var reversedNames = [String]()
    
    for name in names {
        reversedNames.insert(name, at: 0)
    }
    
    0 讨论(0)
  • 2020-12-08 20:55
    func reverse(array: inout [String]) {
        if array.isEmpty { return }
        var f = array.startIndex
        var l = array.index(before: array.endIndex)
        while f < l {
            swap(array: &array, f, l)
            array.formIndex(after: &f)
            array.formIndex(before: &l)
        }
    }
    
    private func swap( array: inout [String], _ i: Int, _ j: Int) {
        guard i != j else { return }
        let tmp = array[i]
        array[i] = array[j]
        array[j] = tmp
    }
    

    Or you can write extension of course

    0 讨论(0)
  • 2020-12-08 20:56

    Like this, maybe:

    names = names.enumerate().map() { ($0.index, $0.element) }.sort() { $0.0 > $1.0 }.map() { $0.1 }
    

    Oh, wait.. I have to use for loop, right? Then like this probably:

    for (index, name) in names.enumerate().map({($0.index, $0.element)}).sort({$0.0 > $1.0}).map({$0.1}).enumerate() {
        names[index] = name
    }
    
    0 讨论(0)
  • 2020-12-08 20:56

    You can use the swift3 document:

    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    let reversedNames = names.sorted(by: >)
    
    // reversedNames is equal to:
    //   ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
    
    0 讨论(0)
  • 2020-12-08 20:57

    Here the code for swift 3

    let array = ["IOS A", "IOS B", "IOS C"]
        for item in array.reversed() {
        print("Found \(item)")
        }
    
    0 讨论(0)
提交回复
热议问题