简体   繁体   中英

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

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 ?

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.

You don't need to guard against nil . That's the entire point of optionals (or non-optionals). Also, in Swift, when you are testing for nil , if the variable is an optional (which is the only time it could be nil anyhow), you can just say:

if optionalVar { 
    // do stuff
}

This is probably just translated from the Objective-C version by Xcode and isn't made "Swifty."

Another instance of this kind of thing:

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    // Custom initialization
}

The // Custom initialization should go above the super.init() in Swift, but this is just translated from the Objective-C version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM