Member-only story
What is the final class in Swift?
In Swift, the final
keyword is used to indicate that a class, method, or property cannot be overridden or subclassed. When you declare a class as final
, it means that it's the end of the inheritance chain for that class, and it cannot be subclassed further.
Final Class:
final class MyClass {
// Class definition
}
By marking MyClass
as final
, you're explicitly stating that no other class can inherit from it. This can be beneficial in several scenarios:
- Preventing Subclassing: If you have a class whose design or behavior should not be modified or extended, marking it as
final
ensures that its functionality remains intact and cannot be altered by subclasses. - Performance Optimization: The compiler can perform certain optimizations on
final
classes and methods because it knows they cannot be overridden.
Usage:
final class Vehicle {
// ...
}
// This will produce an error, as 'Car' cannot inherit from a 'final' class 'Vehicle'
class Car: Vehicle {
// ...
}
If you mark class final
, it means that it’s the end of the inheritance chain for that class, and it cannot be subclassed further. If you try to implement inheritance it will produce an error, as Car
cannot inherit from a final
class Vehicle
.