Declarations in extensions cannot override yet error in Swift 4

后端 未结 3 1223
情歌与酒
情歌与酒 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:47

    Swift 5

    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()
        }
     }
    

提交回复
热议问题