Fittoburst
Fittoburst

Reputation: 2305

Swift infinite loop while iterating array

I have a protocol defined as...

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

and some code to iterate the returned array (as an NSArray from ObjC) in Swift as...

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

If my reportListObjects array is nil, I get stuck in an infinite loop at the for-loop. Equally, if there is data in the array, it is iterated and 'something useful' is done until the end of my array is reached but the loop is not broken and continues infinitely.

What am I doing wrong? Or is there something blindingly obvious I'm missing here?

Upvotes: 0

Views: 1377

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

You've added a lot of extra Optionals here that are confusing things. Here's what you mean:

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

If datasource has a value, this will iterate over its currentReportListObjects. Otherwise it will iterate over an empty list.

If you did want to break it out, rather than using ??, then you just mean this:

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

There's no need for the intermediate reportListObject:ReportListObject? (and that's the source of your problem, since it accepts nil, which is the usual termination of a generator).

Upvotes: 3

Related Questions