Writing stuff down. Mostly Code.

Swift Sugar For Optional Ternary Operators

It is a common situation that an optional parameter is being passed into a function and that some other parameter needs to be set based on whether or not the optional parameter is nil or contains a value.

A typical way of handling this in Swift might be to use the if-let syntax as so:

This is fine and works correctly. One improvement that may not be obvious is that the dependentParameter can be declared as an unassigned let as long as the compiler can guarantee that it is assigned prior to being used:

So, those constructions work, but for merely assigning a value it’s annoying to use 5 lines of code. Also, I prefer to use if-else blocks for doing some task, rather than for setting values.

I could use a ternary statement, but we can’t use let _ = optionalParameter syntax there for the switching logic. In Objective-C, we can take advantage of the fact that it treats nil the same as false, so we’d have the nice compact: