Search code examples
iosswiftuiviewcontrolleruipageviewcontroller

How does '==' work with UIViewControllers?


In a tutorial for using UIPageViewController, there's a code that goes like this:

if self == parent.pages.first {
    self.label_Back.isUserInteractionEnabled = false
}

Which basically checks if the self is the first controller stack. How does this work?

And also, if we have multiple instances of a controller class in pages array of UIViewController, will doing the firstIndex thing like below work?

/**
 Notifies '_tutorialDelegate' that the current page index was updated.
 */
private func notifyTutorialDelegateOfNewIndex() {
    if let firstViewController = viewControllers?.first,
        let index = self.pages.firstIndex(of: firstViewController) {
            tutorialDelegate?.tutorialPageViewController(tutorialPageViewController: self, didUpdatePageIndex: index)
    }
}

Solution

  • if self == parent.pages.first
    

    These are Cocoa (Objective-C) objects — UIViewController, descended from NSObject:

    • Swift == on an Objective-C object in the absence of an override calls isEqual:, inherited from NSObject.

    • For an NSObject, in the absence of an override, isEqual: defaults to object identity.

    So this is just like Swift ===, i.e. it is true just in case these are identically the same view controller object.