How I Handle Optionals In Swift

Updated to add using map over optionals section - 7th January 2015

Update (26th January 2015) See Beyond `if let` for video of me presentating of much of this content.

Dealing with optionals is unavoidable in any Swift program that interfaces with the Cocoa or CocoaTouch libraries. Realistically that is all of them with a very few limited exceptions. Handling them is often annoying a although I am very glad of the rigour that they enforce on me. In fact I like the rigour so much that I never use implicitly unwrapped optionals (variable declared with !) and I use force unwrapping only in very limited circumstances.

In almost all cases I use combinations of optional chaining and nil coalescing operators with `if let` used where they don't do the job. In this post I'm going to explain how and where I use the different options and give some examples.

Note that this is very much a "How I do it" post and not a "How you should do it" post. It is also what I do this week which may evolve further in future. I take a somewhat radical approach and others may prefer approaches that fail earlier rather keep running in error conditions to the choices I take which are intended to keep running in most circumstances. Do note that there are definitely cases where it is better to stop than continue in an error condition especially where there is risk of corrupting data, losing money or even more serious consequences. Please choose a domain appropriate response. My recent domain has been a consumer app handling network data and not complicated and corruptible user documents or financial or safety critical and the choices you make about operating in unexpected state are different in each one.