如何在Swift 3.0中使用for循环反转数组?

时间:2016-10-06 02:20:54

标签: arrays swift swift3

如何在Swift 3中使用for循环反转以下数组?如何以相反的顺序打印以下数组?

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

在Swift 3.0下的版本的以下链接中有很多答案,但我无法弄清楚将它用于当前版本的Swift。

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

How to iterate for loop in reverse order in swift?

7 个答案:

答案 0 :(得分:12)

这是swift 3的代码

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

答案 1 :(得分:7)

  

以相反的顺序打印数组

像这样:

toDoListReverse.reversed().forEach {print($0)}

答案 2 :(得分:1)

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])

答案 3 :(得分:1)

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

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])
}

答案 4 :(得分:0)

 //suppose you set your array in   self.arrOfJobsList

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

答案 5 :(得分:-1)

Swift 4

let numbers = [10, 50, 40]

for number in numbers.reversed() {

    print(number)
}

// We can reverse an Array without allocating new space for its elements by calling this reversed() method.

答案 6 :(得分:-2)

我在这本书中也被困了一段时间(顺便说一句。例子来自“大书呆子牧场指南”一书)。我在这里使用了“while”循环,但结果似乎是合法的

var toDoList: [String]
toDoList = ["Take out garbage", "Pay bills", "Cross off finished items"]

var numberOfThingInArray = toDoList.count
numberOfThingInArray -= 1

print("Reversed:")

while numberOfThingInArray >= 0 {
    print(toDoList[numberOfThingInArray])
    numberOfThingInArray -= 1
}