user2986119 user2986119 - 5 months ago 16
Swift Question

Reverse For loop; should be easy

This should be easy but i'm making it hard for myself!
I've created a reverse For loop to iterate through a set.
If there are ten numbers in the set, then I could just do this;

for d in (0..<10).reverse() {

print(d)

}


but I want to match against an Int then count backwards in the set like this;

If myInt = 7, then I want to append 7 to an array (which I can do) but also append; 6,5,4,3,2,1,9,8 to the array in that order.

appreciate the help!

Answer

Here you get your array like this :-

let myInt = 7
var outPutArray : NSMutableArray = []
var tempArray : NSMutableArray = []
for d in (0..<10)  {
    if myInt-d <= 0
    {
        if myInt-d != 0
        {
            tempArray.addObject(d)
        }

    }else{
        outPutArray.addObject(myInt-d)
    }

}
outPutArray.addObjectsFromArray(tempArray.reverse())

print(outPutArray)


7, 6, 5, 4, 3, 2, 1, 8, 9

Comments