swift - 无法形成 Range with end < start 在执行 for 循环之前检查范围?

标签 swift macos swift2

我遇到了 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/

相关文章:

ios - 实例化 Realm 对象时出现 EXC_BAD_INSTRUCTION

swift - 可编码 - arrayPropety [AnyObject] : Reference to member 'data' cannot be resolved without a contextual type

ios - 使用 UITextView 在 NSAttributedString 中自动调整图像大小

macos - 在osx特立独行中发布opencv的问题:ld:找不到架构x86_64的符号

arrays - 如何在 Swift 中查询一个 UITableViewController 中的两个自定义单元格?

c - string.withCString 和 UnsafeMutablePointer(变异 : cstring) wrapped into a function

具有多个操作的 Java 键绑定(bind)

phpfmt php格式化扩展错误: phpfmt: php_bin "php" is invalid

ios - SceneKit 场景背景内容 UIImage 数组错误

generics - Swift 2.0 版本的 struct GeneratorOf<T>