Skip to content

Understanding Swift's Final Keyword

Swift, Final Keyword, Inheritance1 min read

When developing applications with Swift, you may come across a situation where you want to prevent other developers from subclassing your class or overriding its methods and properties. Fortunately, Swift provides a simple solution to this problem in the form of the final keyword.

What is final?

The final keyword is a modifier that can be applied to classes, methods, and properties in Swift. When a class is marked as final, it cannot be subclassed. Similarly, when a method or property is marked as final, it cannot be overridden in any subclass.

Here's an example of how to use the final keyword with a class:

1final class MyClass {
2 // class implementation goes here

In this example, the MyClass class is marked as final, which means that it cannot be subclassed by any other class.

Similarly, here's an example of how to use the final keyword with a method:

1class MyClass {
2 final func myMethod() {
3 // method implementation goes here
4 }

In this example, the myMethod() method is marked as final, which means that it cannot be overridden in any subclass of MyClass.

Benefits of Using final

Using the final keyword has some benefits. Firstly, it prevents other developers from accidentally or intentionally changing the behavior of your class by subclassing it and overriding its methods or properties. This can be especially important if you're developing a framework or library that will be used by other developers.

Secondly, using final can improve the performance of your application because the compiler can perform some optimizations when it knows that a class, method, or property won't be subclassed or overridden.

When to Use final

You should use the final keyword whenever you want to prevent subclassing or overriding of your class, method, or property. However, it's important to note that using final may not always be necessary or desirable. For example, if you're developing an open-source library or framework, you may want other developers to be able to extend or customize your code by subclassing it.