I'am using a third-party framework that provides a class whose instances only have properties. In my app, I'd like to add an extra property to this instances. What the appropriate way to do this would it be for this scenario?
a) Extending the framework's class in my app
b) Creating a subclass of the framework's class and define the new property I need
Thanks in advance
The new subclass will inherit all the capabilities of the parent class, but may then be extended to add the missing functionality. Swift extensions provide a useful alternative option to adding functionality to existing classes without the need to create a subclass.
Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.
Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.
Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you don't have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C.
It's
b)
because adding (stored) properties in a class extension is not supported.
There are two important rules for using extensions:
Extensions can add new functionality to a type, but they cannot override existing functionality
Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties
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