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!


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.

  • Wfpfirst Testfirst

    Thanks! I’m new to Swift and programming so these tricks very helpful.

  • Alex

    One little addition: if you don’t care about the index, you can use _ instead:
    for _ in 0..<10 {

  • Looping through the indices of an Array (or in fact, any collection):

  • Stefan

    The code snippets in the first example are not equal. The first block prints 0 through 9, whereas the second one prints 1 through 10.

  • Apokrupto

    I had Swift 2.2 refuse this, then I had to figure out what the author was doing

    for var index = string.startIndex; index < string.endIndex; index = index.successor().successor() {

  • Matthew K

    Here is one I ran into:

    for ( i = 0; i < n; ++i) { … }

    var i = 0
    while i < n {

    i += 1

  • n3x07

    thanks a lot. I really didn’t like the change at all. Now I have a project around 100 warnings in xc0de, not cool at all.

  • Carlos Sanchez

    How would one write the following loop in Swift?
    int i;
    for(i = 0; i <N; i++){
    int j;
    for(j = i; j < N; j++){
    //Do stuff

  • Abhay Deshpande

    awesome !! thank you natasha

  • Check out the Stride function Swift has. It’s sort of the same thing