Swift 4 and Xcode 11: Missing 'window' variable

When trying to run the code after populating the UITableView, I kept getting an error about a missing ‘window’ variable in AppDelegate at the line:

let itemsController = window!.rootViewController as! ItemsViewController

An important clue was that there was no declaration of window in AppDelegate like:

var window: UIWindow?

I eventually tracked this down to the problem documented at https://www.reddit.com/r/hackingwithswift/comments/cdfbcd/project_7_missing_window_variable_in_appdelegate/

To solve this problem, you need to create the ItemStore in SceneDelegate.swift not AppDelegate.swift. My final code in SceneDelegate was:

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
        
        // Create an ItemStore
        let itemStore = ItemStore()
        
        // Access the ItemsViewController and set its item store
        let itemsController = window!.rootViewController as! ItemsViewController
        
        itemsController.itemStore = itemStore
    }
1 Like

Thanks for posting! This helped me out.

Worked perfectly. Thank you.

Thanks but there’s still error when I run and build application
it’s about nil while unwrapping window.
Could you let me know how to solve this please?

803173+1200 PwnerHome[6292:140197] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file PwnerHome/SceneDelegate.swift, line 25