Swift Difficulty-an example of a construction rule in succession

Source: Internet
Author: User

One, two constructors-specifying constructors and convenience constructors
Specifies the constructor: a prerequisite constructor in the class that assigns an initial value to all properties. (some subclasses may not need to display the declaration because the default inherits from the base class)
Convenience constructor: A secondary constructor in a class that assigns an initial value to a property by invoking the specified constructor. (declared only when necessary)
Example

[Plain]View Plaincopy
    1. CLASS FOOD {  
    2.     var name :  string  
    3.     init (name: string)  {   
    4.         self.name = name  
    5.     }  
    6.     convenience init ()  {  
    7.         self.init (name:  " [Unnamed] ")   
    8.     }  
    9. }  

The convenience constructor is declared by the convenience keyword, and you can see that the convenience constructor is constructed by invoking the specified constructor. This is also a key concept: horizontal proxies.
What is an agent: let others help you work
II. rules in the construction process
(a) The constructor chain is the order in which the constructor is called
The rules are as follows:
1.1. Specifies that the constructor must call the specified constructor of its parent class
1.2. The convenience constructor must call the specified constructor in the same class
1.3. The convenience constructor must end with the invocation of a specified constructor
Always say a word: Convenient constructor horizontal proxy, specify constructor upward proxy.
As an example:

[Plain]View Plaincopy
  1. Class base{
  2. var basevar:string
  3. Init (baseinput:string) {
  4. Basevar = Baseinput
  5. }
  6. Convenience init () {
  7. Self.init (baseinput: "")
  8. }
  9. }
  10. Class sub:base{
  11. var subvar:string;
  12. Init (subinput:string,baseinput:string) {
  13. Subvar = Subinput
  14. Super.init (Baseinput:baseinput)//Here is the rule 1.1
  15. }
  16. Convenience init (consubinput:string) {
  17. Self.init (subinput:consubinput,baseinput: "")//Here is the rule 1.2
  18. }
  19. Convenience init () {
  20. Self.init (consubinput: "")//Here is Rule 1.3, because another convenience constructor is called, and the other one facilitates the end of the call to the specified constructor
  21. }
  22. }


(ii) Inheritance and overloading of constructors
In swift, subclasses do not inherit the constructor of the parent class by default.
Constructors ' overloads follow the rules of the constructor chain (1.1-1.3)
The constructor inherits the following rules:
2.1. If no specified constructors are defined in the subclass, the specified constructors for all parent classes are automatically inherited
2.2. If all the parent classes in the subclass are provided with the specified constructor, whether inherited by rule 2.1 or custom implementation, it inherits the convenience constructor of all the parent classes.
Note: subclasses can implement the specified constructor of the parent class by using the subclass convenience constructor in a way that partially satisfies rule 2.2.
Example one:

[Plain]View Plaincopy
    1. Class base{
    2. var basevar:string
    3. Init (baseinput:string) {
    4. Basevar = Baseinput
    5. }
    6. Convenience init () {
    7. Self.init (baseinput: "Basevar")
    8. }
    9. }
    10. Class sub:base{
    11. var subvar:string = "Subvar";
    12. }

Here the subclass does not define any constructors, so rule 2.1, 2.1, will inherit the specified constructors and convenience constructors of all the parent classes
So you can call this

[Plain]View Plaincopy
    1. var Instance1 = Sub ()
    2. var instance2 = Sub (baseinput: "Newbasevar")


Example Two

[Plain]View Plaincopy
  1. Class base{
  2. var basevar:string
  3. Init (baseinput:string) {
  4. Basevar = Baseinput
  5. }
  6. Init (firstpart:string,secondpart:string) {
  7. Basevar = Firstpart + Secondpart
  8. }
  9. Convenience init () {
  10. Self.init (baseinput: "Basevar")
  11. }
  12. }
  13. Class sub:base{
  14. var subvar:string;
  15. Init (subinput:string,baseinput:string) {
  16. Subvar = Subinput
  17. Super.init (Baseinput)
  18. }
  19. }


Here, the subclass simply implements a constructor for the parent class, so it does not inherit the convenience constructor, nor does it inherit another specified constructor
You can only create instances like this.

[Plain]View Plaincopy
    1. var instance = Sub (subinput: "Subvar", Baseinput: "Basevar")


(iii) based on the above two rules, the construction process is divided into two parts
Stage One

    • A specified constructor or a convenience constructor is called;
    • Complete the memory allocation for the new instance (memory has not been initialized at this time);
    • Specifies that the constructor ensures that all the storage properties it introduces have been assigned (the storage attribute is extremely memory-initialized);
    • Specifies that the constructor calls the parent class constructor (parent class constructor property initialization);
    • The constructor that calls the parent class goes up the chain of constructors up to the top. (Ensure that all inherited base class procedures have been initialized.)

Phase II

    • From the top down, the constructor specified by the class in each constructor chain has the opportunity to further customize the instance, at which time the constructor can access self, modify its properties, invoke instance methods, and so on.
    • Finally, the convenience constructor of any constructor will have the opportunity to customize the instance and use self.

Maybe this rule is a little abstract, for example.

[Plain]View Plaincopy
  1. Class base{
  2. var basevar:string
  3. Init (baseinput:string) {
  4. Basevar = Baseinput
  5. }
  6. }
  7. Class sub:base{
  8. var subvar:string;
  9. Func Subprint () {
  10. println ("Can now Invoke instance method")
  11. }
  12. Init (subinput:string,baseinput:string) {
  13. Subvar = Subinput
  14. Super.init (Baseinput:baseinput)
  15. This completes the stage one
  16. Self.subvar = Subinput + "123"//You can call self at this time
  17. Subprint ()//The instance method can also be invoked at this time
  18. }
  19. }

Always: When the memory of the instance of the class is initialized, that is, after calling Super.init (), the phase one is completed.

Third, the compiler security check
Check A

Specifies that the constructor must be initialized before the properties of the class it resides on to delegate the construction task up to the constructor in the parent class. To put it simply, initialize your own storage property first, and initialize it in the super.init of the calling parent class.
Check Two
Specifies that the constructor must first call the parent class constructor, assigning an initial value to the inherited property. This very simple answer, assuming that the inheritance of X, you first to assign a value of 1, and in the call to the parent class constructor, the parent constructor will give X to assign another initial value to ensure that the initialization process is complete, then your assignment 1 is overwritten
Check Three
The convenience constructor calls the other constructors in the same class first, and then assigns the initial value to any attribute. Similar to check two and is also prevented from being overwritten
Check Four
The constructor cannot drink self until the first stage is complete, cannot invoke any instance properties, cannot invoke an instance method


Four, summarize
The procedure for specifying a constructor is this
1. Assigning an initial value to a property of its own
2. Call the base class constructor (Super.init)
3. You can then call self, and instance methods, to store properties. Customize the new value.
Then, let's look at a better example from the official documentation.

[Plain]View Plaincopy
  1. Class Food {
  2. var name:string
  3. Init (name:string) {
  4. Self.name = Name
  5. }
  6. Convenience init () {
  7. Self.init (Name: "[Unnamed]")
  8. }
  9. }
  10. Class Recipeingredient:food {
  11. var quantity:int
  12. Init (name:string, Quantity:int) {
  13. self.quantity = Quantity
  14. Super.init (Name:name)
  15. }
  16. Override convenience init (name:string) {
  17. Self.init (Name:name, quantity:1)
  18. }
  19. }
  20. Class Shoppinglistitem:recipeingredient {
  21. var purchased = False
  22. var description:string {
  23. var output = "\ (quantity) x \ (name.lowercasestring)" {
  24. Output + = purchased? "YES": "NO"
  25. Return output
  26. }
  27. }

The relationship of this constructor chain

Explain

    • Base class food defines a specified constructor and a convenience constructor
    • Subclass Recipeingredient implements all the specified constructors of the base class food, so it inherits the convenience constructor of the base class
    • Subclass Shoppinglistitem does not have a constructor defined, so it inherits all constructors of the base class Recipeingredient. Swift Introductory Series 15-construction rules in succession (difficulty)

Swift Difficulty-the construction rule instance in inheritance is detailed

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.