Subclass or Extend classes in Swift

UIView, UIButton, UIControls, oh gosh!

Steven Curtis

--

Before we start

Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.1, and Swift 5.4

Keywords and Terminology

Class: An object that defines properties and methods in common
Subclass: A class that inherits from a superclass
Superclass: The class that is being inherited from

This article

Background

I wrote an article about the SOLID principles, and mentioned that classes should be open for extension and closed for modification and written some articles about extensions in Swift . At the same time, I’ve written articles about subclassing UIView so which should be done and when?

Which should we use, Extension or Subclassing

The Senior Dev answer

It depends.

OK, that is the common joke about when we need to choose something in computer science so let us actually go into some detail about the reasoning behind this decision before you sit at a computer and try something.

The difference between the two

Extensions

You can only *add* to an existing class, and are not allowed to have stored properties in order to do so. So in effect you can only add new methods and computed vars to add additional functionality to a class.

Because extensions are global this functionality is added to any instance of the class that you extend.

Subclasses

You can add new properties (constant *let* and *var*) and also override functions in order to change code functionality.

A common use of subclassing is `UIViewController` subclasses, and using `UIKit` the first file you see (a ViewController.swift file) will be a subclass of `UIViewController`.

--

--