3
fileprivate func test() {

        guard let w = self.view.window else {
            print("no window")
            return
        }
        guard let rootvc = w.rootViewController as? UINavigationController else {
            print("no rootvc")
            return
        }

        for vc in rootvc.childViewControllers {
            print("CHILD \(vc)")
        }

        for vc in rootvc.viewControllers {
            print("VC \(vc)")
        }
}

the code above shows the same. But whats the difference between childViewControllers and viewControllers ?

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194

2 Answers2

4

According to documentation:

public var childViewControllers: [UIViewController] { get }

childViewControllers: An array of view controllers that are children of the current view controller. (read-only). This property does not include any presented view controllers. This property is only intended to be read by an implementation of a custom container view controller.

var viewControllers: [UIViewController] { get set }

viewControllers: The view controllers currently on the navigation stack.

NOTE: A ViewController also have childViewControllers property. but viewControllers property defined in UINavigationController.

Sahil
  • 9,096
  • 3
  • 25
  • 29
1

ViewControllers are The view controllers currently on the navigation stack. Where ChildViewControllers are An array of view controllers that are children of the current view controller.

The root view controller is at index 0 in the array, the back view controller is at index n-2, and the top controller is at index n-1, where n is the number of items in the array. Assigning a new array of view controllers to this property is equivalent to calling the setViewControllers:animated: method with the animated parameter set to false.

ChildViewControllers property does not include any presented view controllers. This property is only intended to be read by an implementation of a custom container view controller.

You can easily get description about it by Alt + Click on syntax!!

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75