What is the difference between final Class and Class?

Final is class modifier which prevents it from being inherited or being overridden. From apple documentation

You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword (such as final var, final func, final class func, and final subscript).

Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error. Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the extension’s definition.

You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (final class). Any attempt to subclass a final class is reported as a compile-time error.


Use final when you know that a declaration does not need to be overridden. The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection.

Read more:

https://developer.apple.com/swift/blog/?id=27


Classes marked with final can not be overridden.


Why should one care at all whether class can or can't be overridden?

There are two things to consider:

  1. As an API designer/developer, you might have a class in your Framework that can be abused or misused when subclassed. final prevents class to be subclassed—mission accomplished. You can also use final to mark methods, properties, and even subscripts of non-final classes. This will have same effect, but for particular part of the class.
  2. Marking class as final also tells Swift compiler that method should be called directly (static dispatch) rather than looking up a function from a method table (dynamic dispatch). This reduces function call overhead and gives you extra performance. You can read more on this on Swift Developer Blog.

Final means that no one can inherit from this class.

Tags:

Swift