Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

                   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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading