Why is AppDelegate.swift window an optional?

后端 未结 3 2090
灰色年华
灰色年华 2020-12-14 03:47

I was reading Apple docs, when I found this sentence:

The AppDelegate class contains a single property: window.

va

3条回答
  •  我在风中等你
    2020-12-14 04:13

    It becomes more obvious when you create the window programmatically instead of using a main storyboard, which automatically sets the window property.

    You may not want to or not be able to create the window immediately when your delegate object (AppDelegate in your case) is created. Usually you don't need to create the window and set the property until application(_:didFinishLaunchingWithOptions:) was called. So until the window is created and the property is set it will be nil.
    Like Losiowaty already stated this is also the case when the app is started but not displayed to the user - e.g. when just processing location updates or other information in the background.

    If the property would be non-optional then you would be forced to create the window at the moment you create your AppDelegate object which is neither desired nor necessary.

提交回复
热议问题