提问者:小点点

如何在具有范围[dplicate]的for循环中向后迭代


在此 switch 语句的默认情况下,我尝试在 for 循环中向后迭代,在使用 Int 时有一些示例可以做到这一点,但我还没有找到任何变量。

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)
    }

所以我希望从upperindex倒计时到lowerindex


共1个答案

匿名用户

你不能用一个 for ...在。。。陈述。当使用 for ...在。。。语句中,索引变量和范围都是不可变的,您无法控制范围的迭代方式。

但是,您可以使用几种替代方法,例如 while 循环、步幅s 和递归。

如何使用步幅按降序遍历范围的示例:

stride(from: upperIndex, through: lowerIndex, by: -1).forEach({ index in
    let rotationValue = newArray.remove(at: index)
    newArray.insert(rotationValue, at: 0)
})