Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sample iOS app in XCode 6 checks for nil of a non-optional variable?

Tags:

ios

swift

xcode6

In "Master-Details" sample Swift app that comes with XCode 6 in MasterViewController.swift file they define objects like this:

var objects = NSMutableArray()

Then in insertNewObject method they check against nil before using it:

func insertNewObject(sender: AnyObject) {
    if objects == nil {
        objects = NSMutableArray()
    }
    objects.insertObject(NSDate.date(), atIndex: 0)
    let indexPath = NSIndexPath(forRow: 0, inSection: 0)
    self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}

If objects is not optional and objects = nil throws an error, why do they need to guard against nil?

like image 270
Mohsen Avatar asked Nov 11 '22 06:11

Mohsen


1 Answers

That is a bug; I find it surprising that it compiles without an error or warning. (I guess it's probably being turned into a call to isEqual:, passing nil?) Interestingly, the more idiomatic version:

if objects {
    objects = NSMutableArray()
}

Does actually fail; you get an error on the if objects line because you can't test an NSMutableArray for boolean-ness.

like image 64
Jesse Rusak Avatar answered Nov 15 '22 05:11

Jesse Rusak