Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class extension vs. subclassing in Swift?

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

like image 905
AppsDev Avatar asked Aug 08 '16 10:08

AppsDev


People also ask

What is difference between subclass and extension in Swift?

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.

What is Subclassing in Swift?

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.

What is the difference between category and extension?

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.

What is Swift extension class?

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.


1 Answers

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

like image 115
vadian Avatar answered Sep 18 '22 13:09

vadian