0

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?

2
  • Your array is of type ReportListObject (non-optional), but you're for-in says ReportListObject?... and NSArray is probably nil-terminated... change the type in the for-in to be non-optional (or just let it implicitly infer the type)? Commented May 29, 2015 at 16:47
  • Thanks. That worked. Potentially a dangerous trap to fall into!!! Commented May 29, 2015 at 16:57

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.