The final keyword in Swift is often ignored or overlooked. That isn't surprising as it isn't immediately obvious what the benefits are of annotating a class, method, or property with the final keyword. In this episode, you learn about the obvious and less obvious benefits of diligently marking a class, method, or property as final.

Inheritance

As I hinted in the introduction, the final keyword can only be applied to classes and the methods and properties of classes. The compiler throws an error if you apply the final keyword to a type that isn't a class or doesn't belong to a class. In this example, we apply the final keyword to a struct.

What Are the Benefits of the Final Keyword in Swift

What is the purpose of the final keyword? As the name suggests, the final keyword indicates that a class cannot be subclassed. Methods are properties that are marked as final cannot be overridden by subclasses. The compiler throws an error if you try to subclass a final class or a method or property that is marked as final.

What Are the Benefits of the Final Keyword in Swift

What Are the Benefits?

Applying the final keyword to classes, methods, and properties has several important benefits. You already learned about the most obvious benefit. The final keyword prevents a class from being subclassed and it prevents a method or property from being overridden by a subclass.

Clarity

There are several other less obvious benefits, though. A final class cannot be subclassed. That is clear, but it communicates to anyone using the class that it is intended to be used as is. That may seem obvious, but it is quite helpful. Whenever I browse code that I'm not familiar with, it is nice to see proper use of the final keyword. I immediately understand that the class I'm browsing doesn't have subclasses. The same is true for methods and properties.

Misuse

I like that the final keyword can also be applied to methods and properties. It is convenient to mark a method or property as final to lock its implementation in place. This is desired if you design a class that can be subclassed, but you want to lock some of its behavior by marking one or more methods or properties as final.

Performance

An entity that is marked as final helps the compiler optimize your code. This results in shorter compilation times and improved performance. The performance gains are small, though. There are also scenarios in which the compiler applies the final keyword if it knows it can safely do so. Your can learn more about this in How to Use Swift's Final Keyword.

What's Next?

There is a good reason why the final keyword exists and I encourage you to apply it diligently. It avoids easy to miss bugs and makes the code you write easier to understand. The question is why are you not using the final keyword?