Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the 'view' property of UIViewController not optional in Swift?

I noticed that the view property of UIViewController isn't of type UIView? but UIView instead (i.e not optional). Why is that? Aren't UIViewController's views supposed to be nil when not loaded yet?

The offical documentation states the following:

The view stored in this property represents the root view for the view controller's view hierarchy. The default value of this property is nil. .... The UIViewController class can automatically set this property to nil during low-memory conditions and also when the view controller itself is finally released.

From my understanding of Swift optionals, it seems that view should be declared as var view: UIView? since it may be nil at some point. Apple seems to state the opposite, can you explain my why?

What do you think?

like image 515
Nicolas B. Avatar asked Sep 18 '14 09:09

Nicolas B.


1 Answers

It looks like view is a lazy property (but not using the lazy modifier) - in fact if you read the inline comment (cmd+click on the view property to open the source) it says:

The getter first invokes [self loadView] if the view hasn't been set yet. Subclasses must call super if they override the setter or getter.

and about loadView():

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

I presume that:

  • the standard implementation creates an empty view if it is not instantiated otherwise
  • it is backed by an optional variable (not publicly accessible)
  • in case of low memory conditions, the backing variable is set to nil, releasing the view instance
  • if you try to access the property when the backing variable is nil, it creates a new instance

so its implementation should be conceptually similar to:

private var _view: UIView?

var view: UIView {
    if _view == nil {
        loadView()
    }
    return _view!
}

func loadView() {
    if _view == nil {
        // _view = something()
    }
}
like image 193
Antonio Avatar answered Oct 24 '22 19:10

Antonio