【问题标题】:Mutating range of For loops in Swift在 Swift 中改变 For 循环的范围
【发布时间】:2021-11-05 22:16:52
【问题描述】:

我正在尝试设置一个动态范围,该范围在 for 循环内迭代时会发生变化。又名:从索引跳转到索引。

例如:

func func(c: [Int]) -> Int {
    var currentIndex = 0
    
   for i in currentIndex..<c.count 

       currentIndex += 3 //After changing the currentIndex value, will my "i" start from currentIndex?
   
}

所以我从 0 开始,然后是 3,然后是 6,依此类推... 当我运行这段代码时,“i”像往常一样总结为 i = 0, i = 1, i = 2...我可以改变迭代范围吗?

【问题讨论】:

  • 不,你不能。 – 查看How can I do a Swift for-in loop with a step? 以获得更好的解决方案。
  • 您可能正在寻找stride
  • 您想任意改变循环计数器,还是每次都添加一个固定量?如果是前者,请改用 while 循环。
  • stride() 似乎确实是标准解决方案,但您也可以使用“i*3”,但这隐藏了实现。停止条件 (c.count) 可能需要一些其他计算... (c.count/3)
  • 谢谢你们的帮助。第一次看到stride,感觉挺方便的。

标签: arrays swift for-loop


【解决方案1】:

与 cmets 一样,一种强大的解决方案是使用 stride 中的构建。另一种解决方案是

while currentIndex < c.count
{
    //your loop logic
    currentIndex += 3
}

你不需要'i'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多