The "IOS" Swift class inherits, constructs the method, the destructor and so on review

Source: Internet
Author: User

The construction method is more informative and involves some of the rules and concepts that are constructed in swift. This time wrote 7 person to review, plus celebrity xiaoming.

Mark:playground is really a good thing, special practice when writing swift, real-time display is really great!


I. Inheritance and rewriting to prevent rewriting

the 1.1 base class does not inherit any classes . Swift does not want to inherit from the Object class in OC or Java . Defines a class that does not inherit any class , which is a base class .

Class person1{   //This Person1 is the base class    Func Eat () {        println ("Eat a Pig!")}    }

1.2 inheritance . Swift is a single inheritance

Class xiaoming1:person1{    var name = "Xiaoming"}

1.3 rewrite . You must add the keyword override. (Oc,java is not required )

Class xiaohong1:person1{    override Func Eat () {        super.eat ();  You can use super to invoke properties and methods in the parent class        println ("Xiaohong eat a Pig")    }}var xh = XiaoHong1 () xh.eat ()

1.4 Overriding Properties ( storing and calculating properties )

Property overrides can be made with Get/set/willset/didset
A read-only property can be rewritten as a read-write property, and a read-write property cannot be rewritten as a read-only property
That is, the scope of the rewrite can only be small-to-large (Java-like)
When a subclass overrides a property of a parent class, regardless of whether the parent class is a computed or stored property, the overriding procedure is to override the Get/set in it, and the subclass override is the format of the computed property

class person2{var name:string{//Compute attribute set{println ("Person2 set")} get{return "     Person2 "}} Let Age:int = 10//Constant Storage property var Height:int = 175//Variable storage property}class xiaoming2:person2{ Override var name:string{set{super.name = newvalue//Sets the value of the parent class to the new value println ("XiaoMing2 set         ")} get{Return" XiaoMing2 "}} override var age:int{//If the parent attribute is Var, you must have get and set get{println (Super.age) Return (}} override Var height:int{//Override observation properties:        Inherited constants Store properties, read-only computed properties cannot add observers.            didset{//Note where Didset,willset is not possible get/set println ("didset----\ (oldValue)")} willset{ println ("Willset----\ (newvalue)")}}}var xm2 = XiaoMing2 () xm2.name = "XM2" println (xm2.age) xm2.height = 10


1.5 Prevent rewriting (final). with the like Java

You can write final in the properties/methods/classes, etc. before class person3{    final var name = "Person3"}class xiaoming3{    //override var name ...//This will be an error}

second, the constructor

The constructor in Swift has no return value (which is the return ID in OC), and its primary task is to ensure that the new instance completes the correct initialization before the first use.

Init (), which can be overloaded

2.1 Default constructors and overloads with parameter constructors , inheritors

Class person4{    var name:string  //must be initialized or initialized in constructor    //default, without parameter    init () {  //No return value        name = "Xuneng "    }        //with parameter    init (name:string) {  //default is the parameter name as the external parameter name        self.name = name +" Hello "  //and OC in the same, with self . (Use this in Java)    }        With optional parameters. Optional type: Can be empty, or can be assigned later. Initialize to nil    var age:int = ten    init (name:string, age:int?) {        Self.name = name        self.age = age!   Optional parameters must be determined to have (plus!) to assign a value    }    }var P4 = Person4 ()  //default is the var p4_1 without parentheses = Person4 (name: "xn4545945")  // Parameter name as external parameter name var p4_2 = Person4 (name: "Neng", Age:10)

2.1 specifying the constructor (designated initializer) with the convenience Builder (convenience initializer)

2.1.1 Specifies the constructor : Each class must have at least one to ensure that all values are initialized . ( The parent class is initialized based on the parent class 's inheritance.

The 3 constructors in Person4 are the specified constructors, all of which require initialization of all member variables

2.1.2 Convenient constructor ( plus convenience keyword ): Auxiliary constructor . Can be used with a specified constructor in the same class , or it can be used to create an instance with a specific input

Class person5{    var name:string  //must initialize, or initialize        init (name:string) {//Specify constructor        self.name = name + "H" in the specified constructor Ello "    }        Convenience init (name:string, height:int) {  //facilitation constructor. All initialization of member variables is not required        self.init (name:name)        println (height)    }} var P5 = Person5 (name: "xn4545945", height:175)

2.2 constructor chain ( concept ): The specification specifies the invocation relationship between the constructor and the convenience builder .

1) Rule 1: Specifies that the constructor must call the specified constructor of its parent class//2) Rule 2: The convenience constructor must call another constructor called in the same class//3) Rule 3: The convenience constructor must end with a call to a specified constructor

One sentence summarizes the above 3 rules : Specifies that the constructor is called up , and the convenience constructor is called horizontally .




2.3 Two-segment construction process ( concept )

First Stage: Each stored-type property is passed through the constructor of their class toset the initial value。
Second Order stage: When each stored-type attribute value is determined, the two stage begins, giving each class a chance before the new instance is ready to be usedfurther customize their storage-type properties。

The use of two-stage construction processes makes the construction process more secure , while giving each class complete flexibility throughout the class hierarchy.

Swift 's two-segment construction process is similar to the construction process in objective-c . The main difference is stage one , where Objective-c assigns 0 or null values to each attribute ( for example, 0 or nil). Swift 's construction process is much more flexible , allowing you to set custom initial values and handle certain properties without the legal default of 0 or nil the value of the case.


Inheritance of the 2.4 constructor ( concept )

Unlike OC, Swift Neutron class does not inherit the constructor of the parent class by default. (but will automatically inherit if the following 2 conditions are met)
1) If the subclass does not define a specified constructor, then he will actively inherit the parent class's
2) If the subclass provides all the parent classes to specify the implementation of the constructor, then the convenience constructor of the parent class is automatically inherited

Class father{    init () {        println ("Father init")    }    convenience init (name:string) {        self.init ();        println ("Father convenience init")    }}class son:father{    override init () {//subclass implements all the specified constructors of the parent class, thus automatically inherits the convenience constructor of the parent class        println ("son init")    }} var son1 = son () var son2 = Son (name: "Xuneng")  //automatically inherits the convenience constructor of the parent class

2.5 setting default values for properties by closures and functions

The general format of the closure class someclass{let    someproperty:int = {//The entire curly brace denotes a closure of        return 0    } ()//This parenthesis cannot be lost, indicating that the closure is executed immediately. and return value .}
1) If the value of a stored property needs to be specifically customized, you can use a closure or global function class to provide a default value.
2) When a type is created, closures or functions are called, and their return values are assigned to this storage property as default values.
3) When using closures, other parts of the instance are not initialized and therefore cannot be accessed in closures: Other instance Properties/self Properties/instance methods, etc.

Class person6{    Let name:string = {//can do some complicated initialization work in the closure allow        firstName = "Xu" lets        lastName = "Neng"        return FirstName + lastName    } ()}var P6 = Person6 () println (P6.name)


Third, the destruction ( anti-initialization ) Deinit

The anti-initialization function is called immediately before a class instance is disposed
Swift uses ARC to handle the memory management of the instance, just like OC.
Each class has only one anti-initialization function, with no parameters. And does not allow active invocation.
subclass inherits the parent class's inverse initialization function (The release order is similar to Java. free child-to-parent class)
The anti-initialization session method can access all the properties of the instance

Class person7{    var mymoney:int    init () {        Mymoney = ten    }    deinit{        mymoney = 0   //can access variables in the class. But it's useless. Because of the destruction, the member variable does not exist        //can do some cleanup work    }}var p:person7? = Person7 () println (p!. Mymoney) p = nil   //optional type to be set to nil//p!. Mymoney   //error, set to nil


Reference:

The Swift programming Language

Apple Dev Center


Reprint Please specify source: http://blog.csdn.net/xn4545945


The "IOS" Swift class inherits, constructs the method, the destructor and so on review

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.