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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With