iosswiftxcodeloopsstride

How to reset variable of seed on loop using stride with Swift?


I want to reset the variable (seed) on loop using stride with Swift. I have this code perfectly working on C#

for (int i = 0; i <= 10; i++)
{
    //something
    i = 0;  //restart this value when necessary
}

And I'm trying this with swift

for var i in stride(from: 0, to: 10, by: 1){
    //something
    i = 0;  //I need to reset this value when necessary, but not working
}

The variable "i" change for a second, but then returns to the original value and the behavior is different from C#.

Thanks.


Solution

  • As Alexander responded, the exact thing you're actually asking to do is villainous. I'm inclined to believe that a labeled do statement isn't going to be your best option, either, but it's the simplest solution without seeing any more code.

    The following will print 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

    var condition = true
    
    loopReset: do {
      for i in 0..<10 {
        if condition, i > 5 {
          condition = false
          continue loopReset
        }
    
        print(i)
      }
    }