如何反转 Swift 中的数组?

How to reverse an array in Swift?

如何以相反的顺序打印以下数组?

var toDoListReverse = ["Take out garbage", "Pay bills", "Cross off finished items"]

print the array in reverse order

像这样:

toDoListReverse.reversed().forEach {print([=10=])}

这是 swift 3

的代码
let array = ["IOS A", "IOS B", "IOS C"]
for item in array.reversed() {
    print("Found \(item)")
}

Swift 4

let numbers = [10, 50, 40]

for number in numbers.reversed() {

    print(number)
}

// 我们可以通过调用 reversed() 方法来反转一个数组,而无需为其元素分配新的 space。

func reverseArray(values: [Int]) {

    var reversedArray : [Int] = []
    var lastElement : Int = -1
    for _ in values {
        lastElement += 1
    }
    for _ in values {
        reversedArray.append(values[lastElement])
        lastElement -= 1
    }
    print("reversed Array is \(reversedArray)")
}

你可以这样调用这个函数:

reverseArray(values: [1, 2, 3 , 90, 9888 , 654])

 //suppose you set your array in   self.arrOfJobsList

 self.arrOfJobsList =  NSMutableArray(array: self.arrOfJobsList.reverseObjectEnumerator().allObjects).mutableCopy() as! NSMutableArray

可以使用另一种方法,如下所示,使用步幅函数

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

并使用 for 循环作为

let names = ["Apple", "Microsoft", "Sony", "Lenovo", "LG"]
let totalIndices = names.count - 1
var reversedNames = [String]()
for arrayIndex in 0...totalIndices {
    reversedNames.append(names[totalIndices - arrayIndex])
}

如果您不想使用 Swift 提供的“reversed()”方法。

您可以使用下面的通用代码代码。

func arrayReversal<T>(array: [T]) {

  var reverseArr = [T]()
  var count = array.count - 1

  while count >= 0 {
    reverseArr.append(array[count])
    count = count - 1
  }

  print(reverseArr)
}
var namesArray = ["Apple", "Microsoft", "Sony", "Lenovo", "Asus"]
arrayReversal(array: namesArray)

OR

let integerArray = [1,3,2,4]
arrayReversal(array: integerArray)