Prefer Swift's for-in loop over traditional C for loop

I'm sure most of us started our first programming adventures in C. How many times

I'm sure most of us started our first programming adventures in C.

How many times have you written

for (int i = 0; i < blah; i++)

or something similar in countless methods, functions, etc.?

In C, C++, Javascript, Java, it's ubiquitous.

Then I came upon the most glorious programming language ever created, Ruby

for index in 0..5
    puts "Value of local variable is #{i}"

This is obviously equivalent to:

for (int index = 0; i <= 5; i++)

The ease of reading should be obvious in Ruby's typical verbosity. Not that any programmer worth his/her salt can't immediately decipher a traditional for loop.

The idea though is to flow code in a way we read natural language.

So it was no suprise that Swift adopted this for-in loop pattern, and in all cases you should prefer to use this format over the C for loop.

Here's Swift's for-in

for index in 0...5 {
    print("current index is \(index)")

Now notice something slightly different

.. vs. ...

In Ruby .. means inclusive (in the example above 0 to 5 including 5). If you added one more dot, ... you'd get exclusive, meaning 0 to 5 excluding 5 (0,1,2,3,4).

In Swift, not the case, ... means inclusive. There currently isn't an exclusive dot offering, although when Swift was first released I remember there being 2 options. This makes sense, in reality if you need exclusive use, you juse use 1 less in value for your range maximum.

You even have the option to just exclude the variable name if it's not needed.

for _ in 0...5 {

Just remember, that will print 6 not 5 times. A better visualization when you want to do something a set number of times would be to start with 1, 1...5 (visualize needing to do something 5 times).

A good example that I'm currently using that to me reads better is parsring rows and columns in an app:

for rowIndex in 0...self.rows {
    for columnIndex in 0...self.columns {
        // now you have each row and column index.            

Having said that there are without a doubt instances where you need to use a C for loop.

Swift's is slightly different:

for var index = 0; index < 10; index += 2 {
    print("index is \(index)")

Imagine you need to increment by 2, or multiply by 2 each time, or decrease in value, etc.


Popular posts from this blog

Gradient UINavigationBar in Swift

Using Xamarin Android Player with Android Studio

How to shuffle an array in Swift