如何通过一个步骤执行 Swift for-in 循环? [英] How can I do a Swift for-in loop with a step?

查看:27
本文介绍了如何通过一个步骤执行 Swift for-in 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着 删除传统的 CSwift 3.0 中的 -style for 循环,我该怎么做?

for (i = 1; i < max; i+=2) {
    // Do something
}

在 Python 中,for-in 控制流语句有一个可选的 step 值:

In Python, the for-in control flow statement has an optional step value:

for i in range(1, max, 2):
    # Do something

但 Swift 范围运算符似乎没有等价物:

But the Swift range operator appears to have no equivalent:

for i in 1..<max {
    // Do something
}

推荐答案

step"的 Swift 同义词是stride" - Strideable 协议 事实上,由许多实现常见的数字类型.

The Swift synonym for a "step" is "stride" - the Strideable protocol in fact, implemented by many common numerical types.

等价于 (i = 1; i 是:

for i in stride(from: 1, to: max, by: 2) {
    // Do something
}

或者,要获得 i<=max 的等效项,请使用 through 变体:

Alternatively, to get the equivalent of i<=max, use the through variant:

for i in stride(from: 1, through: max, by: 2) {
    // Do something
}

注意 stride 返回一个 StrideTo/StrideThrough,符合Sequence,所以你可以用序列做任何事情调用 stride 的结果(即 mapforEachfilter 等).例如:

Note that stride returns a StrideTo/StrideThrough, which conforms to Sequence, so anything you can do with a sequence, you can do with the result of a call to stride (ie map, forEach, filter, etc). For example:

stride(from: 1, to: max, by: 2).forEach { i in
    // Do something
}

这篇关于如何通过一个步骤执行 Swift for-in 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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