【问题标题】:How to iterate backwards in a for loop with a range [duplicate]如何在具有范围的for循环中向后迭代[重复]
【发布时间】:2018-08-19 03:08:17
【问题描述】:

在此 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 to lowerIndex倒计时

【问题讨论】:

标签: swift


【解决方案1】:

你不能用for ... in ... 语句来做到这一点。使用for ... in ... 语句时,索引变量和范围都是不可变的,您无法控制范围的迭代方式。

但是,您可以使用多种替代方法,例如 while 循环、strides 和递归。

如何使用stride 以降序遍历范围的示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    相关资源
    最近更新 更多