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

I noticed that the view property of the UIViewController not of type UIView? , and UIView instead (i.e. is not optional). Why is this? Are UIViewController views supposed to be nil if they are not already loaded?

The official documentation states the following:

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

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

What do you think?

+5
source share
2 answers

It seems that 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:

A getter first calls [self loadView] if the view is not already set. Subclasses should be called super if they redefine the setter or receiver.

and near loadView() :

Here subclasses should create their own hierarchy of views if they don't use a thread. Never be called directly.

I suppose that:

  • the standard implementation creates an empty view if it is not created otherwise
  • supported by an optional variable (not public)
  • in case of low memory conditions, the substitution variable is set to zero, freeing an instance of the form
  • If you try to access a property when the support variable is nil, it will create a new instance

therefore, its implementation should be conceptually similar:

 private var _view: UIView? var view: UIView { if _view == nil { loadView() } return _view! } func loadView() { if _view == nil { // _view = something() } } 
+3
source

The property is technically non-zero. It initializes the view when the property is opened for the first time. It is called lazy loading . This means that when you gain access to a property, you are guaranteed to receive value. I think that the documentation for this property is misleading if not even mistaken.

0
source

Source: https://habr.com/ru/post/1202863/


All Articles