|< Why don’t Swift classes have a memberwise initializer?||Which classes should be declared as final? >|
In Swift, any class that inherits from a parent class can override the methods and sometimes the properties of that parent class, which means they can replace the parent’s method implementation with one of their own.
This level of customization is really important, and makes our lives easier as developers. Think about it: if someone has designed a brilliant class that you want to use, but it isn’t quite right, wouldn’t it be nice to just override one part of its behavior rather than having to rewrite the whole thing yourself?
Sure it would, and that’s exactly where method overriding comes in: you can keep all the behavior you want, and just change one or two little parts in a custom subclass.
In UIKit, Apple’s original user interface framework for iOS, this approach was used a lot. For example, consider some of the built-in apps such as Settings and Messages. Both of these present information in rows: Settings has rows such as General, Control Center, Display & Brightness, and so on, and Messages has individual rows for each conversation you’ve had with different people. In UIKit these are called tables, and they have some common behavior: you can scroll through all the rows, you can tap on the rows to select one, there are little gray arrows on the right side of the rows, and so on.
These lists of rows are very common, so Apple provided us existing code to use them that has all that standard behavior built right in. Of course, there are some bits that actually need to change, such as how many rows the lists have and what content they have inside. So, Swift developers would create subclasses of Apple’s table and override the parts they wanted to change, giving them all the built-in functionality and lots of flexibility and control.
Swift makes us use the
override keyword before overriding functions, which is really helpful:
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Link copied to your pasteboard.