Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declarations in extensions cannot override yet error in Swift 4

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?

like image 969
J. Doe Avatar asked Jun 18 '17 15:06

J. Doe


People also ask

Can we override function in extension in Swift?

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.

Can we override method in extension?

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.

Which job can Extensions not do in Swift?

Extensions can add new computed properties, but they can't add stored properties, or add property observers to existing properties.

How do I create a class extension in Swift?

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. }


1 Answers

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.

like image 154
Sulthan Avatar answered Nov 02 '22 22:11

Sulthan