Stephen J
Stephen J

Reputation: 2397

Why are two exclamation points needed in optional type not unwrapped?

I was presenting a controller from a noncontroller class so I grabbed the root view, and got the common error of "not unwrapped" so I put in ? and !'s to try or forcibly unwrap, still said window was not unwrapped, so it auto-fixed it by inserting another.

UIApplication.sharedApplication().delegate?.window!!.rootViewController!.presentViewController(blah blah blah... { () -> Void in
        });

Title says it all. My only guess is the window is basically a computed property that gives an optional, of which you must unwrap it?!? (grammar not a typo, just ensuring I end the sentence without an error)

Upvotes: 0

Views: 164

Answers (1)

Qbyte
Qbyte

Reputation: 13243

You need two ! because the type is a nested optional (UIWindow??).

Like this:

let nested: Int?? = 3

// the safe way
if let innerValue = nested {
    // innerValue is of type Int?
    if let unwrapped = innerValue {
        // unwrapped is of type Int
    }
}

Upvotes: 1

Related Questions