对于快速混乱的循环

时间:2017-01-19 02:38:26

标签: swift

所以迅速改变了他们的for循环你无法做到

for (i = 0; i <10; i++){
    //do some stuff
}

你只能做

for i in 0...100 {
   //do some stuff
}

我的问题是ii = i + 1?放在for函数中的0放在哪里但它不起作用。

3 个答案:

答案 0 :(得分:5)

如果您需要增加除1之外的其他内容,则使用步幅创建范围:

    for i in stride(from: 0, to: 10, by: 2) {
        print (i) // 0,2,4,6,8
    }

    for i in stride(from: 0, through: 10, by: 2) {
        print (i) // 0,2,4,6,8,10
    }

    for i in stride(from: 0, through: 10, by: 2).reversed() {
        print (i) // 10,8,6,4,2,0
    }

答案 1 :(得分:0)

你不应该,尝试在for循环中打印i,我应该已经每个循环+1了

答案 2 :(得分:0)

Swift中的

for循环与其他语言中的foreach类似。您可以将每个for循环视为:

foreach i in (a sequence of values) {
    // do stuff
}

提供了不同的结构来帮助您在代码中快速而简洁地构建此序列:

0..<n                               // a sequence from 0 to (n-1)
0...n                               // a sequence from 0 to n
stride(from: 0, to: n: by: 3)       // a sequence from 0 to n-1, jumping 3 values at a time
stride(from: n, to: 0, by: -1)      // a sequence from n down to 1
stride(from: n, through: 0, by -1)  // a sequence from n down to 0