在执行循环之前,无法形成带结束<开始检查范围的范围?

Sil*_*611 5 macos swift swift2.2

我遇到了一些我不太了解的快速代码的变化.

var arr = []
for var i = 1; i <= arr.count; i += 1
{
    print("i want to see the i \(i)")
}
Run Code Online (Sandbox Code Playgroud)

我有一个程序获取一个也可以为空的结果数组.这对于上面的for循环没有问题.现在,苹果希望我将代码更改为以下内容.但是如果数组为空,这将崩溃.

var arr = []
for i in 1...arr.count
{
   print("i want to see the i \(i)")
}
Run Code Online (Sandbox Code Playgroud)

在我做循环之前,我是否真的必须首先检查范围?

var arr = []
if (arr.count >= 1){
    for i in 1...arr.count
    {
        print("I want to see the i \(i)")
    }
}
Run Code Online (Sandbox Code Playgroud)

有更聪明的解决方案吗?

Ham*_*ish 11

如果您只想迭代一个集合,那么使用for <element> in <collection>语法.

for element in arr {
    // do something with element
}
Run Code Online (Sandbox Code Playgroud)

如果您还需要在每次迭代时访问元素的索引,则可以使用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
}
Run Code Online (Sandbox Code Playgroud)

您始终可以在每次迭代时向索引添加一个以访问该位置(以获取范围1..<arr.count+1).

如果这些都不能解决您的问题,那么您可以使用范围0..<arr.count迭代数组的索引,或者如@vacawama所说,您可以使用范围1..<arr.count+1来迭代位置.

for index in 0..<arr.count {

    // do something with index
}
Run Code Online (Sandbox Code Playgroud)

for position in 1..<arr.count+1 {

    // do something with position
}
Run Code Online (Sandbox Code Playgroud)

0..<0不能为空数组崩溃,因为0..<0它只是一个空范围,并且1..<arr.count+1不能为空数组崩溃,因为1..<1它也是一个空范围.

另请参阅@ vacawama下面关于使用stride安全地做更多自定义范围的评论.例如(Swift 2语法):

let startIndex = 4
for i in startIndex.stride(to: arr.count, by: 1) {
    // i = 4, 5, 6, 7 .. arr.count-1
}
Run Code Online (Sandbox Code Playgroud)

Swift 3语法:

for i in stride(from: 4, to: arr.count, by: 1) {
    // i = 4, 5, 6, 7 .. arr.count-1
}
Run Code Online (Sandbox Code Playgroud)

这是startIndex开始范围arr.count的数字,是范围将保持在下面的数字,并且1是步幅长度.如果您的数组的元素少于给定的起始索引,则永远不会输入循环.

  • 最后,如果你的起始值是5,例如,`for var i = 5; 我<= arr.count; i + = 1`然后`stride`就是你的答案:`for for in 5.stride(through:arr.count,by:1)`. (2认同)