DEV Community

Collin Donnell
Collin Donnell

Posted on

The Brilliance of `nil` in Objective-C

I don’t code much in Objective-C these days1 but one thing I miss about it compared to Swift is how nil works.

To be fair to Swift, the concept of “nothing” in Objective-C is kind of a mess, since there’s four different versions of it compared to two in Swift.

nil An empty Objective-C object.
Nil An empty Objective-C class.
NULL Nothing in C.
NSNull Mostly used to represent null in Objective-C collections.

The reason NSNull exists is that Objective-C collections (NSArray, NSDictionary) use nil in other ways. NSArray is nil terminated, so if you did this:

NSArray *array = @[@"a", @"b", nil, @"c"];
// array = [@"a", @"b"] 
Enter fullscreen mode Exit fullscreen mode

You'd only have the first two elements available. In NSDictionary, setting a key to nil removes it from the dictionary, so NSNull is used to say “this exists in the dictionary, and it is nothing.”

The main thing to remember is that if you have a pointer assigned to NSNull or NULL and you try to do something with them, your app will crash. nil on the other hand is kind of magic. nil evaluates to NO (false), and nil as an object always returns nil. That means that because whatever you sent to nil will return nil and that will evaluate to false instead of crashing your app that this:

if (dict != nil && dict.containsObjectForKey[@"a"]) { ... } 
Enter fullscreen mode Exit fullscreen mode

Can become this:

if (dict.containsObjectForKey[@"a"]) { ... } 
Enter fullscreen mode Exit fullscreen mode

This is probably the least-Swift thing ever, but, if you're used to coding in this style, it's fantastic. In a lot (most?) cases where there's a possibility that dict could be nil, the thing you want is for nothing to happen. Way back when Swift was first released, and Brent said switching to Swift “feels like a Jedi who’s trying to switch from a lightsaber to a blaster,” this is what I thought of.

Originally posted on collindonnell.com


  1. Although a lot more than none, and I still think it’s important to know if you’re writing software for Apple Platforms. 

Latest comments (0)