In Swift 3.0, the c-style for statement is deprecated. A bold step to remove a structure that most of us are familiar with to make the language more robust, and to continue the ongoing quest to banish the semi-colon from the lands of Swift forever. (I don’t know what the semi-colon did to Apple, but it was obviously pretty serious stuff)
[sourcecode language=”javascript”]
for var i=0;i<10;i++ {
print(i)
}
[/sourcecode]
The basic for loop is straight-forward enough to replace. Using a for-in loop with a range the above will be:
[sourcecode language=”javascript”]
for i in 0..<10 {
print(i)
}
[/sourcecode]
But what of the more complicated c-style for loops? What if we wanted to count down from 10 to 0?
[sourcecode language=”javascript”]
for var i = 10; i >= 0; i– {
print(i)
}
[/sourcecode]
In this case we could apply a `reverse()` method to the range.
[sourcecode language=”javascript”]
for i in (0…10).reverse() {
print(i)
}
[/sourcecode]
But what if we wanted to count down to >0 rather than >=0? This range only permits a >. We could of course add one to the left side to make it >=1, but if we want to maintain it as is, there is another option: the stride() method. Using the stride() method the above could be written:
[sourcecode language=”javascript”]
for i in 10.stride(to: 0, by: -1) {
print(i)
}
[/sourcecode]
The stride() method permits us the same sort of complexity in our for loops that the c-style for loop gave us. For example, what if we wanted to go up by 2’s?
[sourcecode language=”javascript”]
for var i=0;i<10;i+=2 {
print(i)
}
[/sourcecode]
Again we could use stride().
[sourcecode language=”javascript”]
for i in 0.stride(to: 10, by: 2) {
print(i)
}
[/sourcecode]
So, c-style for statements are dead, long live the stride() method!
Leave a Reply