Tom
Tom

Reputation: 55

About AppDelegate window in swift

here is swift default application code in Appdelecage.swift

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    ...

Can anyone tell me why create a optional var window?

why no like this as default:

var window: UIWindow = UIWindow()

that will be save lots of "?" and "!"

thx

Upvotes: 2

Views: 2577

Answers (2)

John Estropia
John Estropia

Reputation: 17500

The var window declaration is to satisfy an optional declaration specified in the UIApplicationDelegate protocol. You're not required to declare it , but if you do, you are not supposed to set it with your own value. The application will set it to its own window and you're only supposed to read it. you still need to provide it as an optional (UIWindow?) because the protocol declares it as such.

Edit: Oops, I apologize. I've been spoiled by storyboards that I forgot you can actually create the root window programmatically.

Upvotes: -1

matt
matt

Reputation: 534885

The job of UIApplicationMain is to see that your window is nil and create and and assign a window for you. I think that's their reasoning.

But in reality, you can just change the question mark to an exclamation mark.

If you were to supply an actual window, it would also be up to you to frame it, as I do here:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch01p006customWindowInStoryboardApp/ch14p366customWindowInStoryboardApp/AppDelegate.swift

Upvotes: 3

Related Questions