spencer.sm
spencer.sm

Reputation: 20574

For-loop where the step-value is greater than one

In Swift, is there a way to create a for-loop with a step-value greater than one?

In Java, it would be:

for(int i = 0; i < 10; i += 2){
    System.out.println(i);
}

The only way I've found is using a while-loop.

var i = 1
while i < 10 {
    print(i)
    i = i + 2
}

Upvotes: 1

Views: 890

Answers (3)

Daehn
Daehn

Reputation: 557

You can achieve this in Swift using the stride(from:to:by:) function like this:

for i in stride(from: 0, to: 9, by: 2) {
    print(i)
}

Or using a forEach closure:

stride(from: 0, to: 9, by: 2).forEach {
    print($0)
}

Upvotes: 12

Shrawan
Shrawan

Reputation: 7246

Update for Swift-3 syntax

for i in stride(from:0, to: 20, by: 5) {
    print(i)
}

Upvotes: 3

dfrib
dfrib

Reputation: 73186

You can use stride

0.stride(through: 10, by: 2).forEach {
    print($0)
}

/* 0
   2
   4
   6
   8
   10 */

Upvotes: 2

Related Questions