Farewell c-style `for` statement

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)

for var i=0;i<10;i++ {
    print(i)
}

The basic for loop is straight-forward enough to replace. Using a for-in loop with a range the above will be:

for i in 0..<10 {
    print(i)
}

But what of the more complicated c-style for loops? What if we wanted to count down from 10 to 0?

for var i = 10; i >= 0; i-- {
    print(i)
}

In this case we could apply a `reverse()` method to the range.

for i in (0...10).reverse() {
    print(i)
}

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:

for i in 10.stride(to: 0, by: -1) {
    print(i)
}

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?

for var i=0;i<10;i+=2 {
    print(i)
}

Again we could use stride().

for i in 0.stride(to: 10, by: 2) {
    print(i)
}

So, c-style for statements are dead, long live the stride() method!

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with:
Posted in Swift

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: