is there anyway to increment exponentially in swift?

前端 未结 4 1079
悲哀的现实
悲哀的现实 2021-01-27 05:08

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 sw

相关标签:
4条回答
  • 2021-01-27 05:29

    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
    }
    
    0 讨论(0)
  • 2021-01-27 05:33

    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
    
    0 讨论(0)
  • 2021-01-27 05:34

    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)

    0 讨论(0)
  • 2021-01-27 05:49

    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.

    0 讨论(0)
提交回复
热议问题