快速表达具有动态范围的循环 [英] Express for loops in swift with dynamic range

查看:26
本文介绍了快速表达具有动态范围的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

...或者如何在 for 循环条件中使用索引

...or how can I use the index inside the for loop condition

大家好由于我们在 swift 3 中没有 c 风格的 for 循环,我似乎找不到一种方法来表达更复杂的 for 循环,所以也许你可以帮助我.

Hey people Since we're left with no c style for loops in swift 3 I can't seem to find a way to express a bit more complex for loops so maybe you can help me out.

如果我要写这个

for(int i=5; num/i > 0; i*=5)

在 swift 3 中我该怎么做?

in swift 3 how would I do that?

我遇到的关闭是:

for i in stride(from: 5, through: num, by: 5) where num/i > 0 

但是如果我是:5、25、125 等,这当然会一次迭代 5 个块.

but this will of course iterate 5 chunks at a time instead if i being: 5, 25, 125 etc.

有什么想法吗?

谢谢

推荐答案

使用辅助函数(最初定义于 将使用除法的 C 风格 for 循环转换为 Swift 3)

Using a helper function (originally defined at Converting a C-style for loop that uses division for the step to Swift 3)

public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T) -> UnfoldSequence<T, T> {
    let nextState = { (state: inout T) -> T? in
        // Return `nil` if condition is no longer satisfied:
        guard condition(state) else { return nil }
        // Update current value _after_ returning from this call:
        defer { state = next(state) }
        // Return current value:
        return state
    }
    return sequence(state: first, next: nextState)
}

你可以把循环写成

let num = 1000
for i in sequence(first: 5, while: { num/$0 > 0 }, next: { $0 * 5 }) {
    print(i)
}

一个更简单的解决方案是 while 循环:

A simpler solution would be a while-loop:

var i = 5
while num/i > 0 {
    print(i)
    i *= 5
}

但第一种方案的优点是循环变量的作用域仅限于循环体,循环变量是一个常量.

but the advantage of the first solution is that the scope of the loop variable is limited to the loop body, and that the loop variable is a constant.

Swift 3.1 将提供 prefix(while:) 序列方法,然后就不再需要辅助函数了:

Swift 3.1 will provide a prefix(while:) method for sequences, and then the helper function is no longer necessary:

let num = 1000
for i in sequence(first: 5, next: { $0 * 5 }).prefix(while: { num/$0 > 0 }) {
    print(i)
}

<小时>

以上所有解决方案都与给定的 C 循环等效".然而,如果num接近Int.max,它们都会崩溃并且 $0 * 5 溢出.如果这是一个问题,那么你必须检查如果 $0 * 5 在进行乘法运算之前 符合整数范围.


All of above solutions are "equivalent" to the given C loop. However, they all can crash if num is close to Int.max and $0 * 5 overflows. If that is an issue then you have to check if $0 * 5 fits in the integer range before doing the multiplication.

实际上这使循环更简单——至少如果我们假设num >= 5 使循环至少执行一次:

Actually that makes the loop simpler – at least if we assume that num >= 5 so that the loop is executed at least once:

for i in sequence(first: 5, next: { $0 <= num/5  ? $0 * 5 : nil }) {
    print(i)
}

这篇关于快速表达具有动态范围的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆