2

Why var window: UIWindow? not UIWindow!, i.e. why making window optional, isn't each app should have a main UIWindow (without it the app can't function at all) ?!

I saw this answer said it did indeed change from UIWindow! to UIWindow? so it must have a reason. I just can't figure out why. Also, with UIWindow?, the type of the main window becomes double optional, it is really awkward.

Community
  • 1
  • 1
Qiulang
  • 10,295
  • 11
  • 80
  • 129

2 Answers2

1

That's because adding UIMainStoryboardFile key into the app's .plist file (which is added by default) is the reason of instantiation the window.

enter image description here

window rootViewController will contains the initial view controller of the storyboard and it will be visible on the screen.

Test it!

can we let the window nil?

try to remove UIMainStoryboardFile row from the .plist file of the project and try to log the window in application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) method:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // if your removed 'UIMainStoryboardFile' key from the plist, this should prints nil
    print(window)

    return true
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Actually, I know UIMainStoryboardFile creates it (as apple document said). But without a UIWindow the app can't function at all, so what is the purpose of making it optional ? – Qiulang Nov 07 '16 at 08:24
  • because in some case (as mentioned in "Test it!" section in the answer), key might not be exists, so in this case window will be nil and all you will see is a black screen – Ahmad F Nov 07 '16 at 08:38
  • I saw your points but you seem not get mine, e.g. who will make a black screen app that makes the app not function at all ? – Qiulang Nov 07 '16 at 08:40
  • I think I got it... Apple says: "A UIWindow object provides the backdrop for your app’s user interface and provides important event-handling behaviors", which means that the window is a layer that added on top of the black screen, [UIWindow](https://developer.apple.com/reference/uikit/uiwindow). – Ahmad F Nov 07 '16 at 09:05
1

I raised this question to apple engineer and following was his answer,

"An example would be initializer functions on any custom class that is assigned to one of the objects in your storyboard. Initializer functions are run before any other method on that class is called (including -initWithCoder:, which is called on during storyboard loading). They would run while to storyboard is being loaded but before the window object is created and assigned to the application delegate. An initializer function could obtain a reference to the application delegate and attempt to read its window."

Qiulang
  • 10,295
  • 11
  • 80
  • 129