is there anyway to increment exponentially in swift?

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

提交回复
热议问题