如何在Swift 2.2中为语句编写复杂的C风格

时间:2021-07-13 22:25:30

How will I be able to implement a C-style for loop like this in Swift 2.2?

如何在Swift 2.2中实现这样的C风格for循环?

for var level: Double = 10; level <= 100; level += 10 {

}

2 个解决方案

#1


5  

for level: Double in 10.stride(through: 100, by: 10) {
}

or in functional style:

或功能风格:

(1...10).map { Double($0) * 10.0 }.forEach {
    print($0)
}

Please, don't use var for iterators and don't change the value of an iterator from inside the loop.

请不要将var用于迭代器,也不要在循环内部更改迭代器的值。

I give more examples in this answer

我在这个答案中给出了更多的例子

#2


2  

For your specific example, what Sulthan said.

对于你的具体例子,Sulthan说。

More generally, for truly complex ones, any C-style for loop:

更一般地说,对于真正复杂的,任何C风格的循环:

for init; cond; step { statement }

can be converted to while:

可以转换为:

init
while (cond) {
  statement
  step
}

#1


5  

for level: Double in 10.stride(through: 100, by: 10) {
}

or in functional style:

或功能风格:

(1...10).map { Double($0) * 10.0 }.forEach {
    print($0)
}

Please, don't use var for iterators and don't change the value of an iterator from inside the loop.

请不要将var用于迭代器,也不要在循环内部更改迭代器的值。

I give more examples in this answer

我在这个答案中给出了更多的例子

#2


2  

For your specific example, what Sulthan said.

对于你的具体例子,Sulthan说。

More generally, for truly complex ones, any C-style for loop:

更一般地说,对于真正复杂的,任何C风格的循环:

for init; cond; step { statement }

can be converted to while:

可以转换为:

init
while (cond) {
  statement
  step
}