Search code examples
iosswiftoptional-values

Using ? (optionals) in Swift variables


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 '?'


Solution

  • 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.