【问题标题】:How can I do a Swift for-in loop with a step?如何通过一个步骤执行 Swift for-in 循环?
【发布时间】:2016-02-22 15:00:02
【问题描述】:

使用removal of the traditional C-style for-loop in Swift 3.0,我该如何执行以下操作?

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

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

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

但 Swift 范围运算符似乎没有等效项:

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

【问题讨论】:

  • 我没看到那个!我找到了this,这让我得到了答案。我在搜索时(在提问之前)缺少的关键字是“stride”——我使用的是“step”这个词,但没有找到任何有用的结果。然后当我找到 stride 时,我发现 Erica Sadun 的 post on the topic 现在已经过时了。
  • 我认为这应该重新打开。 “for loop with a step/interval”是一个特定的问题,在Swift中具有Stride的唯一答案,与dupe Question不同。

标签: swift


【解决方案1】:

“step”的 Swift 同义词是“stride”——实际上是 Strideable protocol,由 many common numerical types 实现。

(i = 1; i &lt; max; i+=2) 的等价物是:

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

或者,要获得 i&lt;=max 的等价物,请使用 through 变体:

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

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

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

【讨论】:

  • 在swift 3中你可以使用全局函数stride(from:through:by:)stride(from:to:by:),比如for i in stride(from:1, to:max, by:2){...}
  • @MarkoNikolovski 请不要在其他用户的答案中添加代码。我们不想把话放在他们嘴里。相反,添加一个新答案。由于此问题已关闭,您可以为链接的副本添加新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多