Styling an optional `Bool`

So  Russell Finn asked me today if I had any thoughts on styling an Optional<Bool>. His use case is something like this: what if you have an optional variable like Optional<NSWindow>, with a property or method on that type, and want to test against the one case where the value is not-nil and the property or method on that value is meaningful?

For example, what if you have a possible window that’s possibly zoomed? How would you style that in the most readable fashion? There are, of course, a lot of ways to express this:

if let zoomed = window?.isZoomed, zoomed { ... }
guard let window = window, window.isZoomed else { ... }
if let window = window {
    if window.isZoomed { ... }
guard let window = window else { ... }; 
    if window.isZoomed { ... }

and so forth.

I suppose the thing you should be asking yourself is how long the window is of interest. If the only goal is to dezoom it if it’s zoomed, the if approach makes sense. However, if you plan to perform multiple steps, then you’ll want to unwrap the window and then work directly with the unwrapped version.

There’s nothing particularly terrible about stacking conditions into a compound guard or if statement so long as the conditions are related and tell a single step-by-step story. But if they don’t, I’d recommend breaking them down, as in the second two examples.

If it’s a one and done (thanks Dave and Greg), you can compare directly with a truth value:

if window?.isZoomed == true { ... }

I’m afraid, I’d have to know a bit more about the exact circumstances of use to have a stronger opinion. I hope this helps.


  • Surprised you didn’t offer

    if window?.isZoomed == true { }

    Is that a construction that you don’t like? If not, why not?

    • This also plays nicely the mentioned idea of “how long X is of interest”. This case is for “not interested at all”, so no binding necessary.

  • I agree with @gregomni. That’s how I do it.

  • Thanks for giving this so much thought.

    My exact use case is that I have an extension on NSWindow called stopModalWindowOrSheet(withCode:sender:) (*); this method returns a success/failure code but is generally expected to succeed. (If I was fully Swiftifying it, I’d make it throw on failure.) Similarly, my NSWindow property is inside a window controller and so is an optional, but I expect it to be non-nil.

    Given my expectations, I want to call it concisely while logging an error in the unlikely either of my assumptions are false. I’d come up with

    if window?.stopModalWindowOrSheet(withCode: responseCode, sender: sender) != true { ... }

    but wondered if there is a more generally accepted style for this. I checked _Swift Style_ and didn’t find anything, so I asked Erica directly.

    I’m concluding that this style is probably the best in this case.

    (*) adapted from an Objective-C helper from MrNoodle, found on GitHub