1

In the default case in this switch statement, I'm trying to iterate backwards in a for loop, there are examples of how to do this when working with Int's but I haven't found any with variables.

func arrayLeftRotation(myArray: [Int], d:Int) {
        var newArray = myArray
        switch d {
        case 1:
            let rotationValue = newArray.removeLast()
            newArray.insert(rotationValue, at: 0)

        default:
            let upperIndex = newArray.count - 1
            let lowerIndex = newArray.count - d
            for i in lowerIndex...upperIndex {
                let rotationValue = newArray.remove(at: i)
                newArray.insert(rotationValue, at: 0)
            }
        }
        print(newArray)
    }

So I wish to count down from upperIndex to lowerIndex

Martin Muldoon
  • 3,388
  • 4
  • 24
  • 55
  • Some of the answers from here might help you: https://stackoverflow.com/questions/37170203/swift-3-for-loop-with-increment/37250498 – Cristik Mar 10 '18 at 18:22

1 Answers1

1

You cannot do that with a for ... in ... statement. When using a for ... in ... statement, both the index variable and the range are immutable and you have no control over how the range is iterated through.

However, there are several alternatives you can use, such as while loops, strides and recursion.

Example for how to iterate over a range in descending order using a stride:

stride(from: upperIndex, through: lowerIndex, by: -1).forEach({ index in
    let rotationValue = newArray.remove(at: index)
    newArray.insert(rotationValue, at: 0)
})
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116