Swift notes (14)--Construction process

Source: Internet
Author: User
Tags closure

Construction Processin order to generate instances of classes, structs, enumerations, and so on, the preparation process is called the construction process. For this process, we typically define a method to complete, which is called the constructor. Of course, its inverse process, called the destructor, is used to do some cleanup before the instance is released, and to handle it in its own definition.

Set the initial value class and struct body for a stored type property at the moment the instance is generated, you must assign a specific initial value to all of the properties.

Either give the initial value directly when defining the stored-type attribute, or you must specify an initial value in the constructor. Neither of these cases triggers the listener behavior of the stored-type attribute (property observer).
struct MyClass {var number:intInit (){//This is the constructor, it has no return valueNumber = 1//Specify an initial value for the stored-type attribute}}
or struct MyClass {var number:int = 1//directly at the time of storage-type attribute definition. Specify an initial value}
You can also define the constructor yourself and pass in the parameters for it. The property is then initialized with the corresponding initialization: struct MyClass {var number:intInit (num:int){//This is the constructor, it has no return valueNumber = num//Specify an initial value for the stored-type attribute}
Init (num:int, Bytimes:int){//ability to define multiple constructorsNumber = num * Bytimes}}
Let MyInstance1 = MyClass (num:1)//Use the first constructor to generate an instance of let MyInstance2 = MyClass (num:10, Bytimes:3)//using another constructor to generate and An instanceNote: This is slightly different from the previous class method, where Swift provides an external use name for each of the parameters, and this behavior is in the class method. is from the beginning of the second parameter (mentioned in note 11). Of course you can specify an external use name to replace the default behavior of Swift ("_" can still prevent Swift from providing an external use name).
Optional Type PropertiesSuppose we do not assign a value when defining an optional type attribute. Also, if there is no assignment in the constructor, swift sets the value of this property to nil for us.
Constant PropertyBefore the construction process is finished. The value of a constant property can be arbitrarily altered (with the same type of value, of course).Note: Subclasses are not able to alter the constant properties of the parent class.
default constructorSwift provides a default constructor (what the compiler does) for classes that do not have constructors and all properties have an initial value. Not seen in swift code), there has been a class like this: struct MyClass {var number:int = 1}
In this class, we do not specify a constructor, and the number property has an initial value. Then Swift will provide a default constructor so that the number property does equal 1 ... (For beginners, this can be very difficult to understand, first of all, because this is related to memory allocation problem, not to expand the record.) After all the successors have been read, I would also like to write a series of notes on the analysis of the various types of variables in Swift in a memory model. It's time to come back to this question.

)


struct Property List Builder (memberwise initializers for Structure Types)In structs, in addition to the default constructors mentioned above, Swift will take the initiative to accept a "all-in-one list of stored properties with initial values" constructor, provided that we do not write ourselves a constructor for a struct.


struct MyStruct {var name = "1" var number = 2}
Let mystructinstance = mystruct (name: "Hello", number:100) this is equivalent to providing a constructor for Init (name:string, Number:int), But that's what Swift did for us.
constructor proxies for value typesThe constructor can also invoke other constructors as part of the construction process. This process, called the constructor agent.

Value types (structs, enumerations) do not support inheritance, so their constructor proxies differ from the rules and forms of the class's constructor agent. The constructor of a value type is relatively simple, because the class inherits a very many of the stored properties of the parent class, and it is the responsibility of the class to ensure that the inherited property is initialized correctly during the construction process (and so on).


Let's take a look at an official example:



In this example, there are three constructors, and the first one is an empty {}. When this constructor is called: let Myrect = Rect () origin will be (0.0, 0.0), size will be (0.0, 0.0), all is the initial value.


The third constructor (line 12th) calls the second constructor, which can reduce the code of the third constructor. Assuming there is no such a way, then in this position, we will have to copy the contents of the second constructor, put here (this is obviously not good).
class inheritance and construction proceduresSWITF provides two constructors for classes to ensure that all properties can be initialized with values: specifying constructors and convenience constructors
Spit Groove: Originally in order to facilitate communication and defined a variety of names, results in the learning time. has created a great barrier. I do not know if this is not to be tasted lost.

But now that someone has given names to all sorts of calling methods, they are now in official documents. Just let us know, in fact, that's what this thing is all about.

You're ready.


The specified constructors and convenience constructors here say a lot of explanations in official documents, and the concept of names is a big hype. He's got a dizzy head. is simply for the convenience of use and encapsulated a layer of call, ah, around the halo what is the meaning, or temporarily put it first, a moment to say.
constructor Call chainto simplify the invocation relationship between the specified constructor and the convenience builder, Swift specifies three rules:1. The constructor agent must call the specified constructor of its immediate parent class2. The convenience constructor must call other constructors defined in the same class3. The end part of the convenience constructor must call a specified constructor
A handy memory method is (this is on the document): Specifies that the constructor must always be up-to-the-proxy facilitation constructors must always be horizontal proxies
//Spit Groove: It's nice to say that it's a bunch of simple rules to simplify. Say nasty point is not for business purposes, reduce the threshold and made out of the so-called self-motivated deduction of a series of nausea problems.

。。。


An upward proxy means invoking the specified constructor of the parent class. The horizontal proxy means invoking the diagram of the tectonic organs in its own class:

Each large blue wide block represents a class. Each small blue block (written designated) represents the specified constructor, and each Earth-yellow block (written convenience) represents a convenience constructor. This figure is an explanation of the above three rules.
two-segment construction process (two-phase initialization)Classes in swift, including two phases. In the first stage, each stored-type property sets the initial value through their own class constructor. The second stage. Each stored-type attribute is able to further set their customized initialization.
I'm going to take a small piece of code to illustrate the SB in this document (this code is obviously wrong): int Mynuma = 1
Func MyFunc () {Mynuma =Mynumb //At this time mynumb is not defined, nor initialized,It's obviously wrong.}
int mynumb = 2//mynumb definition + initialization
The so-called two-stage construction process is to tell us. Before you use Mynumb. Make sure it is defined and initialized.

。。。。

So. Assuming that the two-segment construction process, the code above is correctly written as follows:


int Mynuma = 1int Mynumb = 2
Func MyFunc () {Mynuma = mynumb}//seems to be not very funny.

。。

。 A whole bunch of descriptive narratives are meant to illustrate the problem.


inheritance and rewriting of constructorsIn swift, subclasses do not inherit the constructor of the parent class by default. However, we occasionally assume that the function of the parent constructor is not powerful enough, and this time it is necessary to rewrite the constructor in the subclass to achieve a specific purpose.
Assuming that you are overriding a specified constructor, after writing our logic, remember to call the constructor of the parent class. Assuming that you are overriding a constructor for an instance, you must call the other specified constructors in this class.


The rewrite of the constructor differs from the overrides of the property, method, and subscript. We don't need to write overridekeyword in front.


inherit from your own active constructorIn the previous notes as well as in the documentation, has been said. Swift does not inherit the constructor of the parent class by default, but in fact, a very diverse example has already explained that it is possible to inherit by itself (to avoid misunderstandings and riots, to throw cabbage, and so on, I have never said ... :))
Swift's constructor inheritance mechanism, to meet the following two points:1. Assuming that the subclass is undefined, no matter what the specified constructor is, it will voluntarily inherit the specified constructors of all the parent classes. 2. Assuming that the implementation of the specified constructor for all the parent classes is defined in the subclass (either by rule 1 or by itself), it will voluntarily inherit all of the parent class's instance-builder.
syntax for specifying constructors and convenience constructorsSpecify the constructor:Init (number of parameters) {function Body}
Convenience Builder:ConvenienceInit (number of parameters) {//There's a conveniencekeyword here .function Body}
Just know that the convenience type constructor can only invoke its own non-convenience constructor in this class.


set the default value of a property with a closure or functionClass MyClass {var mynumbers:int[] ={var tmpnum = int[] ()//Generate a temporary array. Used to assign a value to mynumbers at the end of the closure .For I in 1 ... Ten {tmpnum.append (i)//Join element} return Tmpnum//Closure return value }()  //This () must not be saved, otherwise, the mynumbers is the closure of the function, not the return value of the closure
Func getnumbers ()-int[] {return mynumbers}}
Let myinstance = MyClass () myinstance.getnumbers ()//This is taken to the mynumbers array of the MyClass

Swift notes (14)--Construction process

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.