首页 > 解决方案 > 在 Swift 中改变 For 循环的范围

问题描述

我正在尝试设置一个动态范围,该范围在 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......我可以吗?改变迭代范围?

标签: arraysswiftfor-loop

解决方案


与评论一样,一个强大的解决方案是使用 build in stride。另一种解决方案是

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

你不需要一个“我”。


推荐阅读