Friday, December 12, 2014

Tearing Down Swift’s Optional Pyramid of Doom

Colin Eberhardt:

With Swift, pyramids become an issue when you have to unwrap multiple optional values before performing some logic […] In the above code, the println statement will only be executed if all three of the optional variable a, b, and c are non nil. The more optionals your code relies on, the deeper the nesting becomes.

[…]

It is actually quite a straightforward task to move the nested if-let statements into a utility function, where a given function is only invoked if all the optional parameters are non nil […] The above function unwraps the optional parameters and invokes the given function with the unwrapped results. Notice that the unwrapped variables have the same name, and shadow, the optional parameters, a naming convention proposed by Sam Davies, which I quite like.

This is still less than ideal, though, because now your code is running inside of an anonymous function. You can’t, for example, return out of the original scope. This is an example of where it would be helpful if Swift had macros, although I think this particular use case is important enough that the language should have a built-in syntax.

Update (2014-12-13): Tim Schmitz:

I think it's worth making some tweaks to how optional unwrapping works, and I have two suggestions.

3 Comments RSS · Twitter


That's indeed not ideal. As someone pointed out in the comments of that article, switch is good at handling multiple optional values. And also, there's this trick with tuples: https://gist.github.com/tomlokhorst/f9a826bf24d16cb5f6a3

This reminds me that I should publish the Swift version of MFIndexSetForeach...


@Michel Yes, the combination of switch and tuples in unwrap is much better than if_let.


[…] There’s lots of good stuff here, and it’s really impressive how quickly Apple is moving. Some highlights are performance improvements (especially with the optimizer off), a set data type, and a fix for the pyramid of doom. […]

Leave a Comment