swiftuiviewuiviewcontrollerswift-optionals

What is the purpose of a line of code that says: '_ = viewController.view'?


What is the purpose of the following line of code? It doesn't seem to do anything. If it were in Playground or in a print statement it would at least show something.

_ = masterVC.view

It's in Apple's sample code at Sharing CloudKit Data with Other iCloud Users.

Here's the complete significant code that contains that line of code:

if let masterVC = masterNC?.viewControllers.first as? ZoneViewController {
      _ = masterVC.view
      start ? masterVC.spinner.startAnimating() : masterVC.spinner.stopAnimating()
}

Solution

  • Let's see the doc of view from UIViewController:

    If you access this property when its value is nil, the view controller automatically calls the loadView() method and returns the resulting view.

    Seeing the project code: masterVC.spinner, is a lazy var that in viewDidLoad() will be added as a subview of its UITableView.

    Why do this then?

    Because when you do:

    let someVC = SomeViewController()
    

    Its IBOutlet and its view hasn't been loaded yet. You can reproduce it with getting having a IBOutlet on that VC, or some subview that will be added to the view in viewDidLoad(). Try to access the property, it will be nil for the IBOutlet (and usually crash with if it's declared forced unwrapped), and subview.superview will be nil for the other one.

    That's also why when you use UIStoryboardSegue, in prepare(for:sender:), when you do:

    if let nextVC = segue.destination as? SomeViewController() {
        nextVC.labelIBOulet.text = "someTextToPass" //It will crash for the same reason
    }
    

    There, it's rather common to pass the model (here a simple String) instead of setting the value of the UILabel.

    I personally prefer calling loadViewIfNeeded() instead, in my opinion it's less strange that invoking the view and ignore the returned value.