The final modifier in Swift prevents the class from being inherited and also prevents subclasses from overriding the properties, methods, and subscripts of the parent class. It is important to note that the final modifier can only be used for classes, not for struct (struct) and enumeration (enum), because structs and enumerations can only follow the Protocol (Protocol). Although the protocol can also follow other protocols, it is not possible to rewrite any members of the protocol that follows, which is why structs and enumerations do not require a final decoration.
a few uses of the final modifier
the final modifier can only decorate the class, indicating that the class cannot be inherited by another class, that is, it does not qualify as a parent class. The final modifier can also decorate the properties, methods, and subscripts in a class, provided that the class is not final decorated. Final cannot modify structs and enumerations.
code Example
Final class Train {//todo ...} Class Maglevtrain:train {//compile failed//todo ...}
In the above code, because the train class is final decorated, the compiler will prompt an error when the Maglevtrain class inherits train.
class Train {
final func method ()
{
// Todo ...
}
}
class MaglevTrain: Train {
override func method ()
{// Compile failed // Todo ...
}
}
In the above code, the compiler will prompt an error when the subclass Maglevtrain overrides the method methods of the parent class because the method methods in the train class were final decorated.