0

I am trying to replicate this for loop from some JS code.

for(var i = 1; i < power; i *=2)

But this (obviously) does not work:

for i in 1.stride(to: power, step: i*2)

I get unresolved identifier. Let's say power was 256, then I'd expect the sequence for i to be 1,2,4,8,16,32,64,128.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nick
  • 2,803
  • 1
  • 39
  • 59
  • 1
    Compare https://stackoverflow.com/q/39903503/2976878 & https://stackoverflow.com/q/40070202/2976878 – Hamish Jun 25 '17 at 22:00
  • Thanks @Hamish - might be worth making this an answer? – Nick Jun 25 '17 at 22:09
  • This code do that: `let first = 1 let last = 256 let interval = 2 for f in sequence(first: first, next: { $0 * interval < last ? $0 * interval : nil }) { print("Number: \(f)") }` Take a look at this answer: https://stackoverflow.com/a/37250498/4763963 Good luck! – Mo Abdul-Hameed Jun 25 '17 at 22:16
  • Just use a while loop: `var i = 1; while i < power { // do stuff with i; i *= 2 }`. – vacawama Jun 25 '17 at 23:15

0 Answers0