Hallo jurken en jassen, Leo hier. Today we will talk about a very basic concept in Swift, the final keyword. So keep in mind that this will be a very beginner-friendly article.
In the dynamic world of Swift programming, understanding and effectively using language-specific features is key to writing efficient, robust, and maintainable code. One such feature, often overlooked yet powerful, is the final
keyword.
At its core, the final
keyword is a declaration modifier in Swift, employed to limit the overriding and extension of classes, methods, and properties. Its use signals intent and brings clarity to the code, ensuring that certain functionalities remain unchanged throughout the lifecycle of the program. In Swift, understanding when and why to employ such a restrictive keyword becomes crucial.
The final
keyword isn’t just about imposing limitations; it’s about creating a secure and predictable coding environment. By preventing subclasses from altering critical functionalities, it enhances code stability and can lead to performance optimizations. This is particularly important in large-scale applications where maintaining control over code behavior is essential. And even the Swift Optimization docs support that!
As we embark on this journey to master the ‘final’ keyword in Swift, remember: in programming, every keyword and every line of code is a choice, and understanding these choices is what elevates good code to great code. Let’s dive into the world of Swift’s final
keyword and unlock the potential it holds for optimized coding.
Today we will not talk about SwiftUI, but last two weeks we explored two interesting concepts using it. The first article was about how to read the steps the users did that day and how to control the step counter with HealthKit. The second article was about an interesting technology to create geofences in SwiftUI, using the CLMonitor class.
No more talking, let’s code! But first…
Painting of The Day
The painting I chose for today is called The Last Day of Pompeii, a masterpiece of 1830 by Karl Bryullov.
Karl Pavlovich Bryullov, originally Charles Bruleau and known as “The Great Karl,” was a seminal Russian painter, pivotal in the transition from neoclassicism to romanticism. Born in St. Petersburg on December 12, 1799, into a family of Huguenot descent, Bryullov had an early fascination with Italy.
His most famous work, “The Last Day of Pompeii” (1830-1833), acclaimed by Pushkin and Gogol, established him as a leading European painter. This success led to his triumphant return to Russia, where he joined the elite circles and secured a high position at the Imperial Academy of Arts. Notable for blending neoclassical simplicity with romantic elements in his portraits, Bryullov’s style was characterized by realistic and psychological depth.
His health declined while working at St Isaac’s Cathedral, leading him to spend his final years in Italy after 1849. Bryullov died near Rome in 1852 and was buried at the Cimitero Acattolico.
I chose this painting because it was the FINAL day of Pompeii, got it?
The Problem – What is Final
Keyword in Swift?
You want to dive into the
final
keyword uses in Swift.
The final
keyword in Swift is a powerful yet often understated tool in a developer’s arsenal. It serves a specific purpose: to prevent subclasses from overriding a method, property, or whole class. In essence, marking an entity as final
in Swift puts a definitive end to the inheritance chain, ensuring that the functionality defined remains intac.
To appreciate the uniqueness of Swift’s final
, it’s helpful to draw parallels with similar concepts in other programming languages. For instance, in Java, the final
keyword can be used in a similar context to prevent class inheritance and method overriding. However, Swift’s implementation of final
is more aligned with its overall design philosophy, focusing on safety and performance.
The Syntax of ‘Final’
The syntax for using final
in Swift is straightforward. When applied to a class, it prevents the class from being subclassed. For example:
final class MyFinalClass { // Class definition goes here }
In the case of functions(methods) and properties, final
ensures that they cannot be overridden in subclasses:
class MyClass { final func myFinalMethod() { // Method definition goes here } final var myFinalProperty: String = "FixedValue" }
Understanding the final
keyword is the first step in harnessing its full potential. As we will see in the subsequent sections, the strategic use of final
can have significant implications on the design and performance of your Swift applications.
When a class, method, or property is declared as final
, the Swift compiler can perform optimizations. Since the compiler knows that these elements will not change in subclasses, it can streamline method dispatching, potentially leading to improved performance.
And that is the theme for the next section of the article.
When and Why to Use ‘Final’
One of the key reasons to use final
in Swift is performance optimization. Methods, this mean functions declared in classes, in Swift are dynamically dispatched, which means the program must determine at runtime which method implementation to execute. This flexibility, while powerful, comes with a performance cost. When a method is marked as final
, it enables the compiler to use static dispatch instead, bypassing the runtime lookup and potentially enhancing the performance.
Final
also plays a crucial role in maintaining the integrity of your code. By marking classes or members as final
, you prevent future subclasses from altering their behavior. This can be particularly important in cases where the class or method must maintain a specific behavior or state, and any alteration could introduce bugs or unexpected behavior.
Use Cases for ‘Final’
- Preventing Overrides: If you have a method with a specific implementation that should not change in subclasses, mark it as
final
ensures this consistency. - Securing Core Functionality: In a class hierarchy, the
final
keyword can be used to secure the core functionality of a base class that should not be altered by subclasses. - Designing Immutable Elements: For classes or properties that are meant to be immutable or have a fixed behavior,
final
is an appropriate tool.
The general rule of thumb is that if you have some behavior, property or the class itself that should not be overridden you need to mark it as final
.
Some things you should consider before using final:
- Flexibility vs. Safety: While
final
enhances safety and performance, it reduces flexibility. Before using it, consider whether you need the flexibility of overriding in the future. - Codebase Impact: Overusing
final
can make your code less adaptable and harder to extend. Use it judiciously, especially in libraries or frameworks where you expect others to build upon your classes. - Testing: Sometimes a easy way to test something is to subclass a class only in tests and have access to its private functions and methods.
‘Final’ in Classes, Methods and Properties
Let’s strip down each one of the uses of the final
keyword in Swift.
Using ‘Final’ with Classes
In Swift, applying the final
keyword to a class is a definitive statement. It indicates that the class is complete in its current form and cannot be subclassed. This is particularly useful for ensuring the integrity and security of your class’s functionality.
Example of a final class:
In this example, SecureDataManager
is designed to handle sensitive data. Marking it as final
ensures that its security features can’t be overridden or weakened by subclassing.
final class SecureDataManager { // Class definition with secure data handling methods }
Preventing class inheritance is crucial in scenarios where the exact behavior of a class is essential for the application’s correct functioning. For example, a class designed to interact with a specific hardware component or a class implementing a precise algorithm should be protected from alterations that subclassing could introduce.
Using ‘Final’ with Methods
When a method is marked as final
, it cannot be overridden by subclasses. This is used to lock down the behavior of a method in a class hierarchy.
Example of a final method:
class AnalyticsTracker { final func trackEvent(name: String) { // Implementation for event tracking } }
Here, the trackEvent
method’s implementation is critical to the consistent functioning of the analytics system, so marking it as final
prevents any subclass from altering how events are tracked. Method overriding can be a source of bugs and unexpected behavior, especially in large and complex class hierarchies. By using final
, you make your intent clear and protect critical methods from unwanted changes, ensuring that they behave as expected in all instances.
Applying ‘Final’ to Properties
The final
keyword can also be applied to properties in Swift. When a property is marked as final
, it cannot be overridden in any subclass. This is particularly useful for properties that hold critical data or need to maintain a specific state throughout the lifecycle of an object.
Example of a final property:
class Configuration { final let endpoint: String = "/myendpoint/example/users" }
In this example, endpoint
is a crucial part of the configuration, and its integrity is vital for the application’s functionality. Marking it as final
ensures that no subclass can alter this value. Really neat, huh?
We also need to think about some code design considerations. Mostly in the overriding capabilities and runtime access speed.
- Preventing Overriding: Just like methods, when a property is overridden in a subclass, it can change the expected behavior of the class. Using
final
ensures that the property’s value and behavior remain consistent. - Runtime Access Speed: Similar to methods, marking a property as
final
can also lead to performance optimizations. The Swift compiler can optimize access to final properties, as it doesn’t need to look up the property’s value dynamically.
And that’s it for today!
Conclusion – How to Use Final
Keyword in Swift?
As we conclude this journey through the nuanced world of the final
keyword in Swift, it’s clear that this small but mighty modifier plays a crucial role in shaping efficient, secure, and stable Swift applications.
By understanding and applying final
effectively, developers can harness its power to enhance both the performance and predictability of their code.
Fellow iOS Developers, that’s all. I hope you liked reading this article as much as I enjoyed writing it.
If you want to support this blog you can Buy Me a Coffee or say hello on Twitter. I’m available on LinkedIn or send me an e-mail through the contact page. You can likewise sponsor this blog so I can get my blog free of ad networks.
Thanks for the reading and…
That’s all folks.
Image credit: Featured Painting