I have an extension:
public extension UIWindow {
override public func topMostController()->UIViewController? { ... }
}
but for my topMostController
I get the next error:
Declarations in extensions cannot override yet error
It works well for Swift 3.1, but for Swift 4 I get this error. How can it be fixed? What did they change in Swift 4?
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 in Swift can:
Apple Developer Guide
You are trying to do is similar to what done by this code:
NOTE: If you want to
override topMostController()
then make subclass ofUIWindow
Swift 5.0
Actually there are few problems in OP code:
UIView
(which is superclass ofUIWindow
) doesn't have methodtopMostController()
, that why you can't override it.Apple doesn't encourage
override func
insideextension
:Incase you still want to override function in extension, there are 2 ways:
[A] Mark your function with
@objc dynamic func
in parent class:[B] Override function from build-in classes, which is descendant of
NSObject
.