我遇到了 swift 代码的变化,我不太明白。
var arr = []
for var i = 1; i <= arr.count; i += 1
{
print("i want to see the i \(i)")
}
我有一个程序可以获取一个结果数组,该数组也可以为空。这对于上面的for循环是没有问题的。 现在苹果要我把代码改成下面这样。但如果数组为空,这将崩溃。
var arr = []
for i in 1...arr.count
{
print("i want to see the i \(i)")
}
我真的必须先检查范围再做循环吗?
var arr = []
if (arr.count >= 1){
for i in 1...arr.count
{
print("I want to see the i \(i)")
}
}
是否有更智能的解决方案?
最佳答案
如果你只是想迭代一个集合,那么使用 for <element> in <collection>
句法。
for element in arr {
// do something with element
}
如果你还需要在每次迭代时访问元素的索引,你可以使用 enumerate()
.因为索引是从零开始的,所以索引的范围是0..<arr.count
。 .
for (index, element) in arr.enumerate() {
// do something with index & element
// if you need the position of the element (1st, 2nd 3rd etc), then do index+1
let position = index+1
}
您始终可以在每次迭代时向索引添加一个以访问该位置(以获得 1..<arr.count+1
的范围)。
如果这些都不能解决您的问题,那么您可以使用范围 0..<arr.count
迭代数组的索引,或作为 @vacawama says ,您可以使用范围 1..<arr.count+1
迭代位置。
for index in 0..<arr.count {
// do something with index
}
for position in 1..<arr.count+1 {
// do something with position
}
0..<0
不能为空数组崩溃 0..<0
只是一个空范围,1..<arr.count+1
不能为空数组崩溃 1..<1
也是一个空范围。
另见 @vacawama's comment below关于使用stride
安全地做更多的自定义范围。例如(Swift 2 语法):
let startIndex = 4
for i in startIndex.stride(to: arr.count, by: 1) {
// i = 4, 5, 6, 7 .. arr.count-1
}
swift 3 语法:
for i in stride(from: 4, to: arr.count, by: 1) {
// i = 4, 5, 6, 7 .. arr.count-1
}
这是startIndex
的地方是开始范围的数字,arr.count
是范围将保持在下方的数字,1
是步长。如果您的数组的元素少于给定的起始索引,则永远不会进入循环。
关于swift - 无法形成 Range with end < start 在执行 for 循环之前检查范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37143197/