icekomo icekomo - 4 months ago 13x
Swift Question

For loop update for Swift 2.2 throwing Binary Operator error

I'm trying to update some of my swift code to comply with the swift 2.2 guide lines. I'm trying to update my for loops this is what I have currently

for(var i = 0; persons?.count > i; i += 1){}

and this is what I thought I should be using

for i in (0..<persons?.count){}

But I'm getting this error "Binary operator '..<' cannot be applied to operands of type 'Int' and 'Int?'"

I'm just not sure what I'm missing.


The problem is that persons?.count might be nil and 0..<nil doesn't make any sense. you can easily fix this by using nil coalescing though:

for i in 0..<(persons?.count ?? 0) {

Or if you prefer you could overload the ..< operator to accept an optional as it's second argument:

func ..<<T:ForwardIndexType where T:Comparable>(lower: T, upper: T?) -> Range<T> {
    return lower..<(upper ?? lower)

This allows you to just write:

for i in 0..<persons?.count {

As Sulthan points out in the comments, this is probably not the best solution for your problem though. You should likely handle the case of persons being nil earlier in your code:

guard let persons = persons else {
    // take care of business

for person in persons {