Maihan Nijat Maihan Nijat - 1 year ago 111
Swift Question

How to reverse array with for loop in Swift 3.0?

How can I reverse the following array using for loop in Swift 3? How can I print the following array in reverse order?

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

There are plenty of answers in the following links for version under Swift 3.0 but I couldn't figure it out to use it for current version of Swift.

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

How to iterate for loop in reverse order in swift?

Answer Source

I've never programmed in Swift before. I'm mostly into C# and Python. Seems like they removed or didn't put in a lot of "normal" stuff in Swift 3 that are in other languages. Anyway, here's my take.

We iterate over the array indexes, pulling the item currently at that index and placing at the beginning. enumerated lets us edit the array in place while giving us an index to work with. _ apparently counts as a variable name. (Some languages let you use _ as a discard pile so I thought I'd try it here and it seems to work.)

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

for (i,_) in toDoListReverse.enumerated() {

for item in toDoListReverse {