is there anyway to increment exponentially in swift?

前端 未结 4 1111
悲哀的现实
悲哀的现实 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:33

    Based on @MartinR answer, only improvement is readability of the call:

    // Helper function declaration
    func forgen(
        _ 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
    

提交回复
热议问题