0
votes

Consider the following code block

// self is a UIViewController
let f = self.view.window?.rootViewController?.view.frame

Here f is an Optional wrapping CGRect. As far as I can understand,

  • view is implicitly unwrapped property.(i.e. UIView!).
  • We access the window property of it with optionally unwrapping the optional window property of view. If it has value then access its rootViewController property else do nothing.
  • Similarly we optionally unwrap rootViewController and access its view property.

  • Finally we get frame of view.

Since any of the window or rootViewController can be nil, frame is an Optional.

Am I understanding it correctly. Also why the view property of UIViewcontroller is optional?

2
view of this: rootViewController?.view?Bista
@Mr.Bista view is not optional. it is implicitly unwrapped optional. It can't be nil therefore you can't optional chain it.Leo Dabus
Ya, that's why i was asking.Bista

2 Answers

0
votes

Yes, your understanding is correct.

“Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.”

Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3.0.1).” iBooks.

UIViewController implements lazy loading of its view. The loadView method is responsible for either loading the view hierarchy (from a NIB or Storyboard scene) or creating it through code. As a result, view will be nil between initialisation and when the view propery is first referenced.

0
votes

view is implicitly unwrapped property.(i.e. UIView!).

Correct.

We access the window property of it with optionally unwrapping the optional window property of view. If it has value then access its rootViewController property else do nothing.

The first part is correct, but the second part is a little wrong. If window does not have a value i.e. nil, the code does not do nothing. The whole expression evaluates to nil. In this case, nil will be assigned to f.

Similarly we optionally unwrap rootViewController and access its view property.

Finally we get frame of view.

That's right.

Since any of the window or rootViewController can be nil, frame is an Optional.

Technically, no. frame is still a non-optional type. It only seems like an optional because all those unwrapping you did. f is an optional though.

Also why the view property of UIViewcontroller is optional?

The purpose of UIViewController is to control and manage a UIView. When UIViewController is initialized, there isn't neccessarily a view for it to manage! The view is loaded just before viewDidLoad is called (in the loadView method). That's why you do all the adding subviews code in viewDidLoad instead of in the initializer.