Swift Alternatives to C-style for-loops

Starting in Swift 3.0, C-style for-loops will be gone from Swift! You can read the full Swift Evolution proposal here.

Last week, I talked to an iOS developer who was upset by this (it is a long-held habit after all!) and was confused by what to use as an alternative. @twostraws did a great write-up on the new Swift 2.2 features and what to use instead, so I’m going to write it down here for my own (and your) reference.

Here are the more-readable Swift alternatives.

Looping n times

Looping n times in reverse

Looping with Stride

Looping through Array Values

Reverse Looping through Array Values

Looping Through an Array with Index

Looping Through Array Indices

Thanks Pyry Jahkola for the tip in the comments!

Don’t Forget Higher Order Functions!!!

I won’t go into detail here, but instead of looping, consider if Swift’s higher order functions such as map, flatMap, filter, reduce, etc can do the job and prioritize using them instead!

Conclusion

I tend to use pretty simple for-loops, so these seem good enough for me. However, if you have another configuration that I’m missing, let me know in the comments!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.