2

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

This is how I've been treating it since the onset of Swift as well (I flip it to an exclamation mark). If something happens to where application(didFinishLaunchingWithOptions:) got called and the window somehow couldn't be programmatically created, there's probably something pretty crash-worthy going on.
-1

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.

4 Comments

Then how would you supply a UIWindow subclass?
@matt You're right, I don't know why I forgot about this. Probably should rest soon.
There's no place in a storyboard to override the window class. The point is that if you're using a storyboard you must cooperate with all the stuff that UIApplicationMain does for you, as I explain here: apeth.com/iOSBook/ch14.html#_the_window
@matt I know we can't specify the window class. I was saying that I got used to using storyboards that I forgot about being able to set the window (and the rootViewController) ourselves (as opposed to being automagically created when we specify a main storyboard).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.