使用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
}
答案 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
会返回符合StrideTo
的StrideThrough
/ Sequence
,所以您可以对序列执行任何操作,您可以使用致电stride
(即map
,forEach
,filter
等)。例如:
stride(from: 1, to: max, by: 2).forEach { i in
// Do something
}