Declarations in extensions cannot override yet error in Swift 4

夙愿已清 提交于 2019-11-30 05:33:43

It will work if you make the base implementation @objc. See Hamish's answer for a detailed explanation about the internals.

Overriding methods declared in extensions is a bit tricky to do correctly. Objective-C supports it, but it's not absolutely safe. Swift aims to do it better. The proposal is not completed yet.

Current version of the proposal available here.

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

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

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

Apple Developer Guide

You are trying to do is similar to what done by this code:

class MyClass: UIWindow {
    func myFunc() {}
}

extension MyClass {
    override func myFunc() {}
}

NOTE: If you want to override topMostController() then make subclass of UIWindow

Swift 5.0

Actually there are few problems in OP code:

  1. UIView (which is superclass of UIWindow) doesn't have method topMostController(), that why you can't override it.

  2. Apple doesn't encourage override func inside extension:

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

  3. Incase you still want to override function in extension, there are 2 ways:

[A] Mark your function with @objc dynamic func in parent class:

class Vehicle {
    @objc dynamic func run() { /* do something */ }
}

class Car: Vehicle { }

extension Car {
    override func run() { /* do another thing */ }
}

[B] Override function from build-in classes, which is descendant of NSObject.

 extension UIWindow {
    // UIWindow is a descendant of NSObject, and its superclass UIView has this function then you can override
    override open func becomeFirstResponder() -> Bool {
        ...
        return super.becomeFirstResponder()
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!