Swift C-style loop

256 Views Asked by At
for (var i = 1; i < 1024; i *= 2) {
    print(i)
}

How can this be done with for in loop?

The given solution is for += operator not *= operator. Please provide a solution for *= thanks.

1

There are 1 best solutions below

15
On BEST ANSWER

In Swift 3 you can do

for f in sequence(first: 1, next: { $0 < (1024 / 2) ? $0 * 2 : nil }) {
    print(f)
}

The concept of the sequence function is described in the documentation.

Printing an infinite list is easy, the code would just be

for f in sequence(first: 1, next: {$0 * 2}) {
    print(f)
}

Since we want the program to stop at some point, we us the ternary operator ? to terminate the list once we reach the maximum value. Since the last value we want to print is 512, the last value we have to double is 256. For 512 which does not satisfy the condition < (1024 / 2) we have nil and thereby stop.