Friday, March 25, 2016

To Optional or Not to Optional: IBOutlet

Curtis Herbert:

UIKit was written during the era of nil messaging, and I’ve come to realize it isn’t safe to 100% assume IBOutlets can’t be nil. Going forward I’ll be using optionals for my IBOutlets. I have a task in my bug tracker to scrub all my IBOutlets to covert them from implicitly unwrapped to standard optionals. A few extra question marks never hurt anyone; I’d rather my app not crash.

Update (2016-03-30): Scott Berrevoets:

Applying these three rules means you properly use the optional semantics.

2 Comments RSS · Twitter


I'd be curious to know where and when those IBOutlets were nil and how you're supposed to handle it when they are. Sure, you can make it optional and avoid crashing, but if an IBOutlet is in fact nil, something has gone pretty wrong. To guard every time you use an IBOutlet to pop the VC or some other measure seems prohibitive, perhaps a nil outlet deserves a crash?


Chris Snazell

Given that UIViewController was designed to lazily load / constuct its view and to then unload it again it's pretty likely that an IBOutlet will be nil at some point during a view controller's existence. Assuming a UIViewController's IBOutlets are non-nil, as Apple does in its Swift "best practice", seems to be wilfully ignorant of how UIKit actually works.

It's the continuing presence of this kind of disonance between how the APIs work & how Apple wants us to think they work with Swift that keeps me in Objective-C.

In general there seems to be a kind ongoing villification of nil that I don't really understand. I appreciate it can be a source of errors but I'd suggest that accepting it's going to around as long as we use reference types and learning how to work with it makes more sense than trying to relegate it to a vestigial existence trapped in the attic like some gibbering relative in a Victorian romance.

Leave a Comment