Fixing a Deprecated Swift For Loop

Getting deprecated errors from the latest version of Xcode claiming your Swift For Loop is obsolete? Not a problem! Apple has decided to remove the C style traditional for loop for something a bit simpler and a little more elegant.

Trying to use something like below?

for var i = 0; i <= 20; i++ {
// some iterating code here that will run 21 times
}

Then try the new Swift For Loop version:

for i in 0…20 {
// some iterating code here that will run 21 time
}

The ellipses acts as your conditional statement. For your counter i, iterate from 0 to 20. You can even make the statement a little more conditional. If you want your for loop to iterate on the condition that your counter is less than something use:

for i in 0.. // some iterating code here that will run 20 times
}

But what if you need to iterate over an array of data? That’s easy!

Our Array:
let arrayData = [“One”, “Two”, “Three”, “Four”, “Five”]

for data in arrayData {
// some iterating code that prints out each value in the array
}

More commonly in my code, I find I am using the count of an array as a conditional statement. This is just as easy.

for i in 0.. // some iterating code that will run 5 times where 5 is the number it items in arrayData
}

And finally, if you are simply running code that looks like the first for loop we used that doesn’t really make use of the iterator i, then it’s completely unnecessary. Simply use something like below:

for _ in 1…20 {
// some iterating code that will run 21 times
}

Apple is constantly trying to differentiate Swift from Obj-C and it’s parent C by making things shorter, quicker, and more elegant. Hopefully this will help relieve some of that frustration caused by the sudden onslaught of deprecation warnings offered by Xcode when you open up your project!

Here is a more detailed and in-depth look at iteration in Swift.

 

Happy Iterating!

Leave a Reply

Your email address will not be published. Required fields are marked *