It will take about 1 minutes to finish reading this article.
In Swift, the keyword final
is used to mark classes, properties, or methods, preventing them from being inherited or overridden. Using final
ensures that specific classes, properties, or methods cannot be inherited or overridden by other classes, thus enhancing the safety and stability of the code. Here are some common use cases:
Class: Declaring a class as
final
prevents other classes from inheriting it. This is useful when you intentionally design a class that should not be inherited or when you want to ensure that specific behaviors of a class will not be altered.1
2
3final class MyClass {
// Class definition
}Method: Declaring a method within a class as
final
prevents subclasses from overriding it. This is useful when you want to ensure that the behavior of a method remains unchanged or unaltered.1
2
3
4
5class BaseClass {
final func myMethod() {
// Method implementation
}
}Property: Declaring a property within a class as
final
prevents subclasses from overriding it. This is useful when you want to maintain the immutability of a property’s value.1
2
3class BaseClass {
final var myProperty: Int = 5
}
Using the final
keyword ensures that your code is more secure and predictable, preventing unexpected inheritance or overriding behavior.