Overrides in class extensions

Hi there!

the Swift book says:

Extensions in Swift can:

• Add computed instance properties and computed type properties
• Define instance methods and type methods
• Provide new initializers
• Define subscripts
• Define and use new nested types
• Make an existing type conform to a protocol

NOTE
Extensions can add new functionality to a type, but they cannot override existing functionality.

However, in practice we can override methods in class extensions:

class ViewController: UIViewController {}

extension ViewController {
    override func viewDidLoad() {}
}

This seems to be incompatible with what the book claims:

… cannot override existing functionality ...

So, my questions are:

• Why are overrides allowed in class extensions?
• Am I reading the book wrong? :)

R+

1 Like

Did you ever get an answer to this? I read at some places that overriding methods in extensions is considered bad, but no "official" statements.

This only works in Objective-C runtime for Objective-C sub-classes, hence it worked with your ViewController object. It's not a bad thing, in fact the generics manifesto mentions it as one issue we want to solve one day.

1 Like