Swift: Avoiding C-Style For-Loops
C-style for-loops will be removed in Swift 3. This may seem a little bit strange at first sight. But Swift has some features that allow better loop structures.
C-style for-loops
Let’s start by looking at the following C-style for-loop:
let programmingLanguages = ["Swift","Objective-C","Java"] for var i = 0; i < programmingLanguages.count; i++ { print("index: \(i), value: \(programmingLanguages[i])") }
It works, but it’s neither very handy nor very “swifty”. In fact, it’s not so easy to learn and also not very easy to memorise.
For-in Loop
The for-in loop provides enough functionality to achieve the same result. But first, let’s take a look at a simpler version:
for language in programmingLanguages { print("value: \(language)") }
It works, but it has one disadvantage: You don’t have access to the index. For some scenarios this is absolutely sufficient, but sometimes you need the index. No problem, we can solve this by using a tuple and the enumerate() function:
for (index,language) in programmingLanguages.enumerate() { print("index: \(index), value: \(language)") }
No we have everything we need! And in my opinion this syntax is much easier to read than the C-style syntax.
But how about dictionaries? Here you can also use a very easy syntax:
let plattformLanguages = ["Android":"Java","iOS":"Swift"] for (key,value) in plattformLanguages { print("key: \(key), value:\(value)") }
In this case it’s not even necessary to call a method on the dictionary. You can just use the for-in syntax combined with a tuple.
Swift 3
Of course you could still argue whether it’s a very good or a very bad idea that C-style for-loops will be removed in Swift 3. On the one hand you’ll have to refactor existing code and you won’t have a choice anymore. But on the other hand this will force developers to use a syntax that’s just better. So in my opinion it’s a good step.
How about you? Do you think it’s a good idea that C-style for-loops will be removed in Swift 3? Please provide a comment below!
References
Title Image: @gregdx / shutterstock.com