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
}
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.
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.
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.
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.
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.
Yes, you can extend a final class. That extension has to follow the usual rules for extensions, otherwise it's nothing special.
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.
An extension may not contain stored properties but you can add methods inside.
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