Class extension vs. subclassing in Swift?
Asked Answered
C

2

9

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

Coachandfour answered 8/8, 2016 at 10:50 Comment(0)
S
16

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

Scram answered 8/8, 2016 at 10:53 Comment(1)
@Coachandfour Extensions are useful as you can easily use them in multiple projects with just simple copy paste.Riane
C
8

It depends on what is the behaviour you are expecting to achieve.

Extending: You can only add new methods and computed vars, but you will achieve seamless effort in your code. the new functionality is available anywhere without adding new classes in your code

Subclassing: You can add new vars and override function but there is a bigger footprint in your code. You will need to use that specific subclass throughout your project.

I guess it is more of a design question.

My suggestion: if the entire project needs this new behaviour use extensions, otherwise subclass.

Cadence answered 8/8, 2016 at 11:24 Comment(2)
Thank you too for your answerCoachandfour
I think the last point is often overlooked. Extensions are global so they affect parts of code that may not want the complexity. For that reason I think they should be avoided in this situation.Hydrosome

© 2022 - 2024 — McMap. All rights reserved.