0

I'm trying to set a dynamic range which changes while iterating inside a for loop. Aka: Jumping from index to index.

For example:

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

So i starts with 0, then it will be 3, then 6 and so on... When I run this code, "i" sums up as usual like i = 0, i = 1, i = 2... Can I mutate the iteration range?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
artikes123
  • 153
  • 1
  • 8
  • 3
    No, you can't. – Have a look at [How can I do a Swift for-in loop with a step?](https://stackoverflow.com/q/35556850/1187415) for a better solution. – Martin R Sep 09 '21 at 08:49
  • 4
    You are probably looking for [stride](https://developer.apple.com/documentation/swift/1641347-stride) – vadian Sep 09 '21 at 08:49
  • Do you want to arbitrarily mutate the loop counter, or do you want to add a _fixed_ amount to it every time? If it is the former, use a while loop instead. – Sweeper Sep 09 '21 at 08:55
  • 1
    `stride()` seems to be indeed the standard solution, but you could also use "i*3", but that's hiding the implementation. The stop condition (c.count) might need some other calculation... (c.count/3) – Larme Sep 09 '21 at 08:56
  • Thank you for your helps guys. First time seeing stride, which seems pretty handy. – artikes123 Sep 09 '21 at 10:43

1 Answers1

0

As in comments, one powerful solution is using build in stride. Another solution is

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

you don't need an 'i'.

Amais Sheikh
  • 421
  • 5
  • 12