Junior — Middle
What is the purpose of the final modifier and in which cases is its use justified?
sobes.tech AI
Answer from AI
The final modifier in Swift is used to prevent overriding a class, method, or property in subclasses. If a class is declared as final, it cannot be inherited. If a method or property is marked as final, it cannot be overridden.
Using final is justified in the following cases:
- When you want to ensure that the behavior of a class or method is not changed in subclasses, which increases code safety.
- For performance optimization, as the compiler can better optimize calls to
finalmethods. - To avoid errors related to incorrect overriding.
Example:
final class NetworkManager {
func fetchData() {
// implementation
}
}
// Attempting to inherit will cause an error
// class CustomNetworkManager: NetworkManager {} // Error
class BaseClass {
final func doSomething() {
print("Base method execution")
}
}
class SubClass: BaseClass {
// override func doSomething() {} // Error, method is final
}