Declarations in extensions cannot override yet error in Swift 4

后端 未结 3 1221
情歌与酒
情歌与酒 2020-12-29 19:44

I have an extension:

public extension UIWindow {
    override public func topMostController()->UIViewController? { ... }
}

but for my

3条回答
  •  悲哀的现实
    2020-12-29 19:48

    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

提交回复
热议问题