Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift override function in extension

If I have a class:

class Spaceship<FuelType> {
    function prepareForLiftoff() throws {
        //Start the countdown!
    }
}

I originally assumed that I would be able to override prepareForLiftoff without subclassing by adding an extension:

extension Spaceship where FuelType: CollectionType {
    func prepareForLiftoff() throws {}
} 

This code doesn't compile though, the error says invalid redeclaration of the function, which makes sense.

My question is: Is there anyway to override a function of a particular class? In other words can I replace the functionality under certain conditions like the example above where FuelType: CollectionType. If not, is there any other workaround or way to achieve that behavior (maybe declaring another protocol, idk)

Now that I think about it more, I would have to say that's not possible because what's to stop someone from overriding any of the standard library functions?

like image 434
barndog Avatar asked Nov 23 '15 01:11

barndog


People also ask

Can I override function in extension Swift?

It is not possible to override functionality (like properties or methods) in extensions as documented in Apple's Swift Guide. Extensions can add new functionality to a type, but they cannot override existing functionality.

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.

How do you override a function in Swift?

In Swift Inheritance, the subclass inherits the methods and properties of the superclass. This allows subclasses to directly access the superclass members. Now, if the same method is defined in both the superclass and the subclass, then the method of the subclass class overrides the method of the superclass.

Can we override protocol in Swift?

The only case that doesn't work is a class that inherits from a base that declares conformity but doesn't provide its own "non-default" implementation - in that case the protocol extension's default is "baked-in" to the base class, and cannot be overridden or re-defined.


1 Answers

From the documentation:

Extensions can add new functionality to a type, but they cannot override existing functionality.

The documentation lists carefully and precisely what an extension is allowed to do.

As to your question:

Is there anyway to override a function of a particular class

Yes, it's called subclassing.

like image 63
matt Avatar answered Oct 12 '22 07:10

matt