C-Style for loops deprecated in Swift. How to increment by x?

Discussion in 'iOS Programming' started by chrono1081, Mar 31, 2016.

  1. chrono1081 macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar
    #1
    Hi guys,

    C-style for loops have been deprecated in Swift, but I can't find a replacement for how to do something like this:

    Code:
    for i = 0; i < 100; i+=2 {
    //Do stuff here
    }
    The only way I can currently get it working is something like:

    Code:
    for case let in 0...100 where n % 2 == 0
    
    But I don't feel like using the modulo operator is the correct approach. Can someone more knowledgable than me in Swift explain how we should handle incrementing by something other than 1? I couldn't find anything in Apples docs or on Stack Overflow. Thanks.
     
  2. Azl macrumors member

    Joined:
    Jul 21, 2012
    Location:
    Karlsruhe, Germany
    #2
    Code:
    var i=0
    while(i<100){
        i+=2
    }
    
    One option...
     
  3. tyche, Mar 31, 2016
    Last edited: Mar 31, 2016

    tyche macrumors 6502

    Joined:
    Jul 30, 2010
    #3
    Use stride

    Code:
    for i in 0.stride(through: 100, by: 2) {
    print(i)
    }
    
    for more complicated conditional checks in For loops, you will likely have to move to a while loop.
    --- Post Merged, Mar 31, 2016 ---
    In your example, I guess I should have used to: instead of through: but you get the idea.
     
  4. chrono1081 thread starter macrumors 604

    chrono1081

    Joined:
    Jan 26, 2008
    Location:
    Isla Nublar

Share This Page