TL;DR: Why can you override NSViewController methods in a subclass using an extension when the Swift Programming Guide implies that extensions cannot be used to override functions?
In the Swift Programming Guide - Extensions section, it states:
Extensions can add new functionality to a type, but they cannot override existing functionality.
However, I routinely override NSViewController in an extension on my subclass. Example:
class ViewController : NSViewController {}
extension ViewController {
// This is legal and does not generate a compiler error.
// The method viewDidLoad() is declared in NSViewController itself.
override func viewDidLoad() {
super.viewDidLoad()
}
// This is legal and also does not generate a compiler error.
// The method addChild() is declared in an extension on NSViewController.
//
override func addChild(_ childViewController: NSViewController) {
super.addChild(childViewController)
}
}
If you look at the Swift generated interface for NSViewController, the method addChild is defined in an extension. So the extension in my subclass is overriding a method defined in an extension in its parent class.
Presumably this is allowed because NSViewController is an Objective-C class. Attempting to use the same pattern in a Swift-only class yields a compiler error.
But I've found very little documentation on this behaviour and was curious:
- What are the rules for overriding a method in an Objective-C class?
viewDidLoad,viewWillAppearand several otherNSViewControllermethods are not defined in an extension whereas most others are. Does it matter if my subclass overrides them in an extension or not?- I assume the
@objcdecorator is playing an important role in this. Is there any documentation out there describing how@objcaffectsoverridesuch that it us allowed in extensions? Or is this behaviour supported becauseNSViewControlleris ultimately anNSObject?
macOS 10.15 Beta 5, Xcode 11 Beta 5