Using ? (optionals) in Swift variables

1.3k views Asked by At

What exactly is the difference between a property definition in Swift of:

var window: UIWindow?

vs

var window: UIWindow

I've read it's basically an "optional" but I don't understand what it's for.

This is creating a class property called window right? so what's the need for the '?'

2

There are 2 answers

0
Tim On BEST ANSWER

The ? identifier means that the variable is optional, meaning its value can be nil. If you have a value in your code, declaring it as non-optional allows the compiler to check at build time if it has a chance to become nil.

You can check whether it is nil in an if statement:

var optionalName: String? = "John Appleseed"

if optionalName {
    // <-- here we know it's not nil, for sure!
}

Many methods that require a parameter to be non-nil will declare that they explicitly need a non-optional value. If you have an optional value, you can convert it into non-optional (for example, UIWindow? -> UIWindow) by unwrapping it. One of the primary methods for unwrapping is an if let statement:

var greeting = "Hello!"

// at this point in the code, optionalName could be nil

if let name = optionalName {
    // here, we've unwrapped it into name, which is not optional and can't be nil
    greeting = "Hello, \(name)"
}

See The Swift Programming Language, page 11 for a brief introduction, or page 46 for a more detailed description.

0
Rudolf Adamkovič On

UIWindow? means that the value may be absent. It's either an UIWindow instance or nothing.