When would you use an extension (or a category in Objective-C) instead of using a subclass and vice-versa?

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.

With extensions, you can only add new methods and computed variables. However, you can achieve smoother integration into your code since the new functionality is available anywhere without having to add new classes to your codebase.

Subclassing can allow you to override methods of a superclass with custom implementations of methods, as well as adding additional functionality.

With subclassing, you can add new variables and you can override functions, but there is however a bigger footprint in your code and furthermore, you will need to add references to that specific subclass throughout your project wherever you make use of the added functionality.

In many cases, in real-world use cases, developers tend to use categories or extensions when an entire project needs (or could benefit from) a new behaviour, in other cases they will tend to use subclass.

Extensions and categories are most often used to add features like methods, initializers, computed properties and subscripts to an existing class without the need to create and reference a new subclass. This can prove particularly powerful when using extensions to add functionality to the built-in classes of the Swift or Objective-C language and the iOS SDK frameworks.

Let’s examine some typical use cases to get a better idea of how we typically use these approaches in real-world applications.

Subclassing Example

Use Case: A Custom UIButton

Extension Example

Use Case: Add functionality to String

 

Since extensions are global, at least within a module, functionality that is added using extensions will be available to any instance of a class and extension on that class.

Loading

Last modified: February 19, 2022