Final modifier to avoid overloading in swift

Source: Internet
Author: User
Tags modifier

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.