11. How to use final?

It will take about 1 minutes to finish reading this article.

In Swift, the keyword final is used to mark classes, properties, or methods, preventing them from being inherited or overridden. Using final ensures that specific classes, properties, or methods cannot be inherited or overridden by other classes, thus enhancing the safety and stability of the code. Here are some common use cases:

  1. Class: Declaring a class as final prevents other classes from inheriting it. This is useful when you intentionally design a class that should not be inherited or when you want to ensure that specific behaviors of a class will not be altered.

    1
    2
    3
    final class MyClass {
    // Class definition
    }
  2. Method: Declaring a method within a class as final prevents subclasses from overriding it. This is useful when you want to ensure that the behavior of a method remains unchanged or unaltered.

    1
    2
    3
    4
    5
    class BaseClass {
    final func myMethod() {
    // Method implementation
    }
    }
  3. Property: Declaring a property within a class as final prevents subclasses from overriding it. This is useful when you want to maintain the immutability of a property’s value.

    1
    2
    3
    class BaseClass {
    final var myProperty: Int = 5
    }

Using the final keyword ensures that your code is more secure and predictable, preventing unexpected inheritance or overriding behavior.