如何使用步骤执行Swift for-in循环?

时间:2016-02-22 15:00:02

标签: swift

使用removal of the traditional C-style for-loop in Swift 3.0,我该如何处理?

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

在Python中,for-in控制流语句具有可选的步骤值:

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

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

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

1 个答案:

答案 0 :(得分:85)

&#34;步骤&#34;的Swift同义词是&#34; stride&#34; - Strideable protocol实际上由many common numerical types实施。

相当于(i = 1; i < max; i+=2)

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

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

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

请注意,stride会返回符合StrideToStrideThrough / Sequence,所以您可以对序列执行任何操作,您可以使用致电stride(即mapforEachfilter等)。例如:

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