0
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.

Ghulam Ahmed
  • 129
  • 1
  • 7
  • Why would you want to do it another way? The way you have it is pretty optimal. – Bathsheba Dec 20 '16 at 14:06
  • 2
    @Bathsheba this way is not possible in Swift 3. – Fogmeister Dec 20 '16 at 14:07
  • 4
    Similar: [Converting a C-style for loop that uses division for the step to Swift 3](http://stackoverflow.com/questions/39903503/converting-a-c-style-for-loop-that-uses-division-for-the-step-to-swift-3) and [Express for loops in swift with dynamic range](http://stackoverflow.com/questions/40070202/express-for-loops-in-swift-with-dynamic-range) – Martin R Dec 20 '16 at 14:07
  • To be fair I did not find the dupe immediately. The google terms were "swift range step". The selected answer solves this *exact* problem. – Mad Physicist Dec 20 '16 at 14:09
  • @MadPhysicist I believe that one solves it for `+=2` but not `*=2` – Fogmeister Dec 20 '16 at 14:10
  • @Bathsheba C style loop is no longer valid in swift 3. – Ghulam Ahmed Dec 20 '16 at 14:10
  • 2
    If I were you I'd add that to the question. To keep charlatans like me away. (But why the deuce would a language committee want to deprecate the C-style loop?!) – Bathsheba Dec 20 '16 at 14:11
  • I'm just curious as to why there is only one close vote when this is so obviously a dupe. – Mad Physicist Dec 20 '16 at 14:14
  • @Bathsheba: See https://github.com/apple/swift-evolution/blob/master/proposals/0007-remove-c-style-for-loops.md for the rationale, and links to the discussion. (That does not mean that everybody agreed with the decision :) – Martin R Dec 20 '16 at 14:42

1 Answers1

4

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.