We all know what the
final keyword to a class/property is for.
- To prevent overriding (obvious)
- To optimize runtime
This optimization tip provided by Apple explains how it optimizes runtime by directly accessing a class/property without a (virtual) vtable lookup.
However, most developers did not know the compiler is smart enough to automatically infer the final keyword.
It was explained in Apple’s blog.
1. Need NOT add for private
If you declare a class/property as
fileprivate, their visibility are already restricted to the current file. Read this on Swift access levels.
The compiler is smart enough to infer them as
final. Adding the keyword is redundant.
2. Need NOT add for internal
The compiler can also infer for the default
internal access level, but only if you enable Whole Module Optimization (WMO) under Building Settings > Compilation Mode > Whole Module.
What WMO does is that all the files are optimized TOGETHER, therefore the compiler can infer across all.
All Release build configuration should have it enabled, so that it optimizes for runtime. While your Debug build config might not have it, it is okay.
3. Only add for public
But if you have
public, then you’re likely providing a library that will be used by others.
In that case, the compiler cannot infer. So if you’re sure the class/property is not override-able, then you should add
final to achieve optimization.
Just 1 scenario where you need to add
final. So please don’t add everywhere 😄