Swift for loop and beyond

February 18, 2016

Swift for loop and beyond

For many people, who are beginning with Swift, one question arises at one point or another: how do I do for loop in Swift? One might go with a simple C-styled approach, which actually works, for now:

for var i = 1; i <= 5; i++ {
    print(i) // 1, 2, 3, 4, 5
}
However, I would strongly discourage one from doing so, as in Swift 3.0 this version of Swift loop is most likely to be removed. I suggest looking at this reference here: Swift evolution.
Pssst, by the way, ++ and -- operators are to be eliminated as well, see here: no more ++/-- operators.


For loop Swift style

Now Swift goes away from C style coding and has its own ways of doing for loops, in particular utilizing for-in loops like this:

let numbers = [1, 2, 3, 4, 5]
for i in numbers {
    print(i) // 1, 2, 3, 4, 5
}

The result is exactly the same, but in this case it follows Swift's language style. You might say that what if you don't want to make an array of integers, feels kinda dumb, isn't it? You know what? I agree. So lets make it even Swiftier:

for i in 1...5 {
    print(i) // 1, 2, 3, 4, 5
}

/*
  Just in case you wonder how to make it go just until
  the end, but not including it.
*/
for i in 1..<5 {
    print(i) // 1, 2, 3, 4
}

Yes, we are doing it much better, cleaner and easier. And it looks better too, comparing to the C-styled for loop, isn't it? OK, but what if I want to make an increment of two or three, for example? We could do this as C-styled for loop, but how the hell do I do this with this for-in loop?
With stride my friend, with stride.

Stride

Now with strides you can achieve quite the same result, but in a more cleaner look, as for me. Not many people know about this method. It will surely add you some points amongst your coder friends when you do it like this, while they do in in old C-style:

for i in 1.stride(through: 5, by: 2) {
    print(i) // 1, 3, 5
}

/*
  Just in case you wonder how to make it go just until
  the end, but not including it.
*/
for i in 1.stride(to: 5, by: 2) {
    print(i) // 1, 3
}

Swift forEach

In case you want to look even cooler - you could enjoy working with forEach Swift method on an CollectionType'd object like this:

let numbers = [1, 2, 3, 4, 5]
numbers.forEach { print($0) } // 1, 2, 3, 4, 5

Comments

comments powered by Disqus