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?
If a protocol defines a method, and provides a default implementation in an extension, a class can override that method, and the override will be called for any reference to the instance, even if the reference's type is declared as the protocol.
Extension methods cannot be overridden the way classes and instance methods are. They are overridden by a slight trick in how the compiler selects which extension method to use by using "closeness" of the method to the caller via namespaces.
Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.
Creating extensions is similar to creating named types in Swift. When creating an extension, you add the word extension before the name. extension SomeNamedType { // Extending SomeNamedType, and adding new // functionality to it. }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With