Search code examples
iosswiftfor-loopvar

iOS/Swift: How to add 1 to i in a loop for for a specific value and how to retrograd a 'loop for' for specific moment?


I try to add 1 to i in a loop for in a specific moment? When I do this, it comes to the "normal" value instantly at the begining of the loop.

for var i in (0..<10)
    {
    if (i == 2)
       {
       i += 1
       }
    }

EDIT:

Concret code:

                   for var i in (0..<models.count) 
                    {
                        if (i > 0 && models[i].label1 == models[i-1].label1)
                        {
                            models[i-1].slots.append(contentsOf: models[i].slots)
                            models.remove(at: i)
                            i -= 1
                           
                        }
                    }

Solution

  • In for loops in Swift, the variable (i) is treated as a let constant, and you cannot mutate it inside the loop.

    That seems right. Being able to mutate a loop variable inside the loop can lead to all sorts of unexpected side-effects.

    You can use a while loop to get the same effect:

    The following works:

    var i = 0
    while i < 10  {
        print(i)
        if i.isMultiple(of: 2) && Int.random(in: 1...3) == 2 {
            i -= 1
        }
        i += 1
    }
    print("Done")
    

    This code throws a compiler error:

    for index in 1...10 {
        if index.isMultiple(of: 3) {
            index += 1 // <- Error: "left side of mutating operator isn't mutable: 'index' is a 'let' constant"
            print(index)
        }
    }