Final classes are ones that cannot be inherited from, which means it’s not possible for users of your code to add functionality or change what they have. This is not the default: you must opt in to this behavior by adding the
final keyword to your class.
Remember, anyone who subclasses your class can override your properties and perhaps also your methods, which offers them incredible power. If you do something they don’t like, bam – they can just replace that. They might still call your original method as well as their replacement, but they might not.
This can be problematic: perhaps your class does something really important that mustn’t be replaced, or perhaps you have clients on a support contract and you don’t want them breaking the way your code works.
Much of Apple’s own code was written before Swift came along, in an earlier language called Objective-C. Objective-C didn’t have great support for
final classes, so Apple usually resorted to large warnings on their site. For example, there’s a very important class called
AVPlayerViewController that is designed to play movies, and its documentation page has a large yellow warning saying: “Subclassing AVPlayerViewController and overriddng its methods isn’t supported, and results in undefined behavior.” We don’t know why, only that we shouldn’t do it. There’s another class called
Timer that handles timed events like an alarm, and there the warning is even simpler: “Do not subclass Timer”.
In Swift it used to be the case that final classes were more performant than non-final classes, because we were providing a little bit more information about how our code would run and Swift would use that to make some optimizations.
That hasn’t been true for a while, but even today I think many people instinctively declare their classes as final to mean “you shouldn’t subclass from this unless I specifically allow it.” I certainly do this a lot, because it’s another way I can help folks understand how my code works.
SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Link copied to your pasteboard.