【问题标题】:Swift infinite loop while iterating array迭代数组时的Swift无限循环
【发布时间】:2015-05-29 16:42:46
【问题描述】:

我有一个协议定义为...

@objc protocol MyDatasource : class {
    var currentReportListObjects:[ReportListObject] { get };
}

还有一些代码在 Swift 中迭代返回的数组(作为 ObjC 的 NSArray)...

if let reportListObjects = datasource?.currentReportListObjects {
    for reportListObject:ReportListObject? in reportListObjects {
        if let report = reportListObject {
            // Do something useful with 'report'
        }
    }
}

如果我的 reportListObjects 数组为 nil,我会在 for 循环中陷入无限循环。同样,如果数组中有数据,则对其进行迭代并完成“有用的事情”,直到到达数组的末尾,但循环不会中断并无限继续。

我做错了什么?还是我在这里遗漏了什么明显的东西?

【问题讨论】:

  • 您的数组是ReportListObject 类型(非可选),但您是for-in 表示ReportListObject?... 而NSArray 可能是nil-已终止...将for-in 中的类型更改为非可选(或者只是让它隐式推断类型)?
  • 谢谢。那行得通。可能会掉入一个危险的陷阱!!!

标签: ios arrays swift loops


【解决方案1】:

您在这里添加了很多额外的 Optional,这些都是令人困惑的事情。这就是你的意思:

for report in datasource?.currentReportListObjects ?? [] {
   // Do something useful with 'report'
}

如果datasource 有一个值,这将遍历它的currentReportListObjects。否则它将遍历一个空列表。

如果您确实想打破它,而不是使用??,那么您的意思就是:

if let reportListObjects = datasource?.currentReportListObjects {
    for report in reportListObjects {
        println(report)
    }
}

不需要中间的reportListObject:ReportListObject?(这是问题的根源,因为它接受nil,这是生成器的通常终止)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2023-03-20
    • 2021-07-10
    • 1970-01-01
    • 2018-01-21
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多