转换forEach而不弃用for循环?

时间:2016-03-24 05:19:58

标签: swift swift2 swift2.2

我使用forEach声明,但我想将其转换为for-loop。但是,现在不推荐使用C风格的for-loop

以下是我尝试转换的内容:

items.indices.forEach { fromIndex in
  ...
}

如何使用向前兼容的for-loop

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法之一:

let arr = ["a", "b", "c", "d", "e", "f", "g"]
let startIndex = 3
let increment = 2

for var i in startIndex..<arr.count {
    print(arr[i], terminator: " ") //d e f g
}

for i in startIndex.stride(to: arr.count, by: increment) {
    print(i, terminator: " ") //d f
}

for (index, element) in arr.enumerate() {
    print(index, terminator: " ") //d f a b c d e f g
}

答案 1 :(得分:0)

这里是good article我找到了Swift 2.2中的更改。

至于你的问题,如果你想使用传统的c样式循环,新语法将是:

for var i in 0..<items.indices.count {
    print("index: \(i)")
}