How to reverse array in Swift without using “.reve

2020-01-31 01:28发布

I have array and need to reverse it without Array.reverse method, only with a for loop.

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

标签: arrays swift
21条回答
一夜七次
2楼-- · 2020-01-31 01:32

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
查看更多
做自己的国王
3楼-- · 2020-01-31 01:32
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)
查看更多
ら.Afraid
4楼-- · 2020-01-31 01:33
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

查看更多
Fickle 薄情
5楼-- · 2020-01-31 01:35
// 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]
查看更多
smile是对你的礼貌
6楼-- · 2020-01-31 01:36
var names:[String] = [ "A", "B", "C", "D", "E","F","G"]
var c = names.count - 1
var i = 0
while i < c {
    swap(&names[i++],&names[c--])
}
查看更多
\"骚年 ilove
7楼-- · 2020-01-31 01:36

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)
}
查看更多
登录 后发表回答