Sinisa Drpa Sinisa Drpa - 4 years ago 71
Swift Question

Unwrapping multiple Swift optionals

I'm trying to rewrite part of ObjC code with Swift, a lot of cocoa object properties return optional value in Swift. Is there better pattern instead of this deep nesting:

if let panel = self.window {
if let screens = NSScreen.screens() {
if let screenRect = screens[0].frame {
let statusRect = CGRectZero

Answer Source

While Leonardo's answer is a good one, it can lead to exceptions unless you know the objects are non-optional, a better pattern is this, which should be regarded as pseudocode:

if let frame = NSScreen.screens()?.first?.frame {
   // Do something with frame.

In other words, use optional chaining (?.), but only use let with the very last part of the chain.

You could also create an operator like this if you want to chain optionals that are of a different type, in which only the value of the last one will be returned:

infix operator ??? { associativity left }

func ??? <T1, T2>(t1: T1?, t2: @autoclosure () -> T2?) -> T2? {
    return t1 == nil ? nil : t2()

if let frame = self.window ??? NSScreen.screens()?.first?.frame {
    // Do something with frame

This is, of course, inspired by Haskell's bind. But as fun as this is, I don't recommend it. I think it's clear as mud. (By the way, the difference between ??? and ?? is that the former does not require the lhs and rhs to be of the same type (or supertype), while the latter does. ??? always returns its rhs or nil.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download