I previously wrote about optionals way back in June 2014, so as I’m working on the book, it’s giving me a good opportunity to look back and compare then and now.
From 1.x to 2.0, we had if let pyramids of doom (too much indent) leading to variable binding constipation blocks (too much condensed reading), and now the yeoman of the guard patterns (too much error handling overhead). Things keep getting better, but I’m not convinced we’re there there yet.
I do think my optionals coverage is some of the most amusing writing I’ve done, and I’ll probably have to throw out about 70% of the humor before this chapter goes to print.
So let me share some of the better bits before they’re gone forever.
- It’s conventional in Swift to use identical symbols in conditional bindings for both wrapped and unwrapped versions. In the following snippet, a mySound symbol is unwrapped within the if-let scope but wrapped outside of it. Using the same symbol makes it clear that you’re working with the same semantics in different states of undress.
- Although useful for accessing values, if-let bindings build into code structures colloquially known as pyramids of doom. Each successive test indents your code further and further to the right, creating a triangle of empty space to the left of first the if statements and then the closing brackets. It’s the sort of code you don’t want to bring home to your project manager — or your mummy.
- In Swift, nil indicates “no value”. Unlike Objective-C, nil is not a pointer. Swift nil indicates a semantic missing non-existance. A count of Monte Cristo. A cup of “not tea”. An honest politician. A nil item means “nothing to see here, move along, move along, move along”.
- With great unwrapping comes great responsibility. You must take care that you properly guard these items to ensure you don’t attempt to unwrap nil.
- In Swift world, it is always Christmas, and there are always presents — or at least variables — to unwrap.
- The nil value is the Swift equivalent of your aunt’s home-crocheted vest. It’s pretty important to check whether an item is nil before unwrapping it.
3 Comments
Thank you for sharing outtakes from your next book on Optionals. Like all outtakes, they may be entertaining but they fail to move the plot or characters forward and therefore end up on the cutting room floor.
“In Swift world, it is always Christmas, and there are always presents — or at least variables — to unwrap” – You made my day!
We have enough dry programming books — Keep the humor, it makes the important points more memorable.