icekomo icekomo - 1 year ago 100
iOS Question

For loop update for Swift 3 throwing Binary Operator error

I'm trying to update some of my swift code to comply with the swift 3 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.

Answer Source

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 ..<(lower: Int, upper: Int?) -> Range<Int> {
    return lower..<(upper ?? lower)

This allows you to just write:

for i in 0..<persons?.count {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download