0

I was wondering if in swift there is a way to manipulate the running index on a for loop.

Using while the program should do the following:

var runIndex = 1
while runIndex <= 100000000 {
    print(runIndex)
    runIndex = runIndex * 10;
}

In java would look as follows:

for (int runIndex=1; runIndex <= 100000000; runIndex = runIndex*10){
    System.out.println(runIndex);
}

I looked at stride but does not seem to be doing factor, it only does linear

for runIndex in stride(from: 1, to: 100000000, by: 10) {
    print(runIndex)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
otc
  • 694
  • 1
  • 9
  • 40

1 Answers1

2

The Swift analog to:

for (int runIndex=1; runIndex <= 100000000; runIndex = runIndex*10){
    System.out.println(runIndex);
}

that gives identical output to:

var runIndex = 1
while runIndex <= 100000000 {
    print(runIndex)
    runIndex = runIndex * 10;
}

is:

for runIndex in (sequence(first: 1) {$0 >= 100000000 ? nil : $0*10}) {
    print(runIndex)
}

See https://developer.apple.com/documentation/swift/2015879-sequence and notice that the documentation actually takes your own use case, i.e. successive powers (of 2), as an example!

matt
  • 515,959
  • 87
  • 875
  • 1,141