I'm working through a tutorial and I noticed that when downcasting I didn't have to use an initializer method of the object. Is the object initialized? In the AppDelegate codebase below, I'm referring to the ItemsTableViewController. All I had to do was say "as!" but didn't need to use an init method or double parenthesis like this "ItemsTableViewController()".
Is the ItemsTableViewController initialized and if so how?
//
// AppDelegate.swift
// HomepwnerThirdTime
//
// Created by Laurence Wingo on 4/26/18.
// Copyright © 2018 Laurence Wingo. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//create an ItemStore when the application launches
let itemStore = ItemStore()
//create an ItemsTableViewController
//set the window property which is of type UIWindow from the UIApplicationDelegate protocol and downcast this property to an initialized ItemsTableViewController by using as!
let itemsController = window!.rootViewController as! ItemsTableViewController
//now access the ItemsTableViewController and set its itemStore property since it is unwrapped in the ItemsTableViewController which needs to be set
itemsController.itemStore = itemStore
//we just set the itemStore property of the ItemsTableViewController! Yayy, WHEW!! Now when the ItemsTableViewController is accessed with that unwrapped ItemStore object then it will be set!!! WHHHHEEEEWWWWW!
return true
}
}
rootViewController
sure is initialised. If it is not then it would have been nil
, and casting it using as!
would have caused an error. Here, by downcasting, you are not doing anything to the VC object. You are just telling Swift that "yes I'm sure this will be a ItemsTableViewController
by the time the code is run, so don't worry about it".
How is the VC initialised then?
This has to do with how iOS handles the launching of an app. When you tap on an app, it opens and a UIWindow
is created. Then the first VC in your storyboard is initialised and set as the rootViewController
of the UIWindow
. After doing all of that, your app delegate is called.
Note that when you are in the didFinishLaunching
method, it's just that the VC has been created. The views in the VC are not loaded. That's what viewDidLoad
is for.