How to reverse an array in Swift?

2020-05-10 11:30发布

问题:

How can I print the following array in reverse order?

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

回答1:

Here is code for swift 3

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


回答2:

print the array in reverse order

Like this:

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


回答3:

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.