Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I extend a final class in Swift?

I'm using a third-party library for a new app that I'm making using Swift. The author of the class/library has made it final using the final keyword, probably to optimise and to prevent overriding its properties and methods.

Example:

final public class ExampleClass {
   // Properties and Methods here
}

Is it possible for me extend the class and add some new properties and methods to it without overriding the defaults?

Like so:

extension ExampleClass {
    // New Properties and Methods inside
}
like image 872
metpb Avatar asked Nov 05 '15 08:11

metpb


People also ask

Can we extend protocol in Swift?

In Swift, you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details, see Protocol Extensions. Extensions can add new functionality to a type, but they can't override existing functionality.

Can we inherit final class in Swift?

Swift gives us a final keyword just for this purpose: when you declare a class as being final, no other class can inherit from it. This means they can't override your methods in order to change your behavior – they need to use your class the way it was written.

What does final class do Swift?

A final class in Swift prevents the class from being inherited. To write a final class, type the keyword final in front of the class definition. You can also mark methods or properties final to prevent them from being overridden in the subclass.

What is the difference between a final class and other classes?

The main purpose of using a final class is to prevent the class from being inherited (i.e.) if a class is marked as final, then no other class can inherit any properties or methods from the final class.

Can you add a property to an existing class in Swift?

We can't add the stored properties to extensions directly but we can have the computed variables . Extensions in Swift can: Add computed instance properties and computed type properties.


3 Answers

Yes, you can extend a final class. That extension has to follow the usual rules for extensions, otherwise it's nothing special.

like image 58
David Reich Avatar answered Sep 28 '22 06:09

David Reich


Extensions (like Objective-C categories) don't allow stored properties.
Methods and computed properties are fine though.

A common (but IMO hacky) workaround in Objective-C was to use associated objects to gain storage within categories. This also works in Swift if you import ObjectiveC.
This answer contains some details.

like image 28
Thomas Zoechling Avatar answered Sep 28 '22 07:09

Thomas Zoechling


An extension may not contain stored properties but you can add methods inside.

like image 39
LoVo Avatar answered Sep 28 '22 07:09

LoVo