Search code examples
iosswiftuiwindow

Declaring UIWindow as let instead of optional var compiles fine. Any pitfalls?


I have seen numerous examples of UIWindow been declared as an Optional variable, like so,

var window: UIWindow?

My app only has one window and it will remain the same throughout its lifecycle. I'd argue it makes more sense to declare it as a constant. And so I did. It doesn't raise any compiler errors (as of iOS 8.2) and seems to work just fine.

Why is nobody else doing this? Are there any pitfalls to doing this?

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    let window: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let viewController = ViewController()

        window.rootViewController = viewController
        window.makeKeyAndVisible()

        return true
     }

Solution

  • There are two parts to your question: let vs var, and optional vs non-optional.

    For the first part, declaring an object property as let just means you expect the property to reference the same object throughout its lifecycle. Makes sense in your AppDelegate for a single-window application.

    For the second part, UIWindow inherits its initializer from UIView; the documentation for UIView says that the initializer can return nil, although the Swift version isn't declared as being failable.

    So if you're dealing with UIViews in other contexts, it probably makes sense to declare the variables as optional, or at least unwrapped, and be able to cope with the results.

    That said, when your program is starting up, if the UIWindow fails to initialize, crashing immediately is probably a reasonable thing to do, as you won't really be able to do anything else. :)

    I don't see any problem with how you've done it, but I'm open to hearing from others too.