Search code examples
iosswiftpropertiessubclassclass-extensions

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


Solution

  • 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