问题
I am trying to write a for loop, where I have to increment exponentially. I am using stride function but it won't work.
Here's c++ code, I am trying to write a swift version.
for (int m = 1; m <= high - low; m = 2*m){}
can you help me, to write this code in swift version?
回答1:
A while-loop is probably the simplest solution, but here is an alternative:
for m in sequence(first: 1, next: { 2 * $0 }).prefix(while: { $0 <= high - low }) {
    print(m)
}
sequence() (lazily) generates the sequence 1, 2, 4, ...,   and prefix(while:) limits that sequence to the given range.
A slight advantage of this approach is that m is only declared inside the loop (so that it cannot be used later accidentally), and that is is a constant so that it cannot be inadvertently modified inside the loop.
回答2:
There is no for loop in Swift, but you can achieve the same result with basic while loop
var m = 1                // initializer
while m <= high - low {  // condition
    ...
    m *= 2               // iterator
}
    回答3:
Based on @MartinR answer, only improvement is readability of the call:
// Helper function declaration
func forgen<T>(
    _ initial: T, // What we start with
    _ condition: @escaping (T) throws -> Bool, // What to check on each iteration
    _ change: @escaping (T) -> T?, // Change after each iteration
    _ iteration: (T) throws -> Void // Where actual work happens
    ) rethrows
{
    return try sequence(first: initial, next: change).prefix(while: condition).forEach(iteration)
}
// Usage:
forgen(1, { $0 <= high - low }, { 2 * $0 }) { m in
    print(m)
}
// Almost like in C/C++ code
    回答4:
Here is a solution using for:
let n = Int(log(Double(high - low))/log(2.0)) 
var m = 1
for p in 1...n {
    print("m =", m)
    ...
    m = m << 1
}
(Supposing that high - low is greater than 2)
来源:https://stackoverflow.com/questions/55495939/is-there-anyway-to-increment-exponentially-in-swift