Reverse For loop; should be easy

It should be easy, but I make it hard for myself! I created a reverse For loop to iterate over the set. If there are ten numbers in the set, I could just do it;

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

        print(d)

}

but I want to combine with Int, then recount in the set as follows:

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

Appreciate the help!

+4
source share
3 answers

Here you get your array as follows: -

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

+1
source

- myInt . , , :

let range: Range<Int> = 0..<10
let pivot: Int = 7

let result = Array(range.startIndex...pivot).reverse()
    + Array(pivot.successor()..<range.endIndex).reverse() // or "pivot + 1"
print(result) // [7, 6, 5, 4, 3, 2, 1, 0, 9, 8]

0 , range (1..<10). .

+3

Like @Sulthan's answer, this one uses strideto build an array:

Swift 2.x:

let (start, end) = (1, 9)
let pivot = 7

let result = Array(pivot.stride(through: start, by: -1)) +
    Array(end.stride(to: pivot, by: -1))
print(result)

Conclusion:

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

Swift 3:

let result = Array(stride(from: pivot, through: start, by: -1)) +
    Array(stride(from: end, to: pivot, by: -1))
0
source

All Articles