[IOS] Swift class inheritance, constructor, and other reviews, iosswift

Source: Internet
Author: User

[IOS] Swift class inheritance, constructor, and other reviews, iosswift

There will be more constructor content, involving some rules and concepts constructed in Swift. This time I wrote 7 persons for review, plus the celebrity XiaoMing.

Mark: Playground is really a good thing. It is really awesome to show it in real time when I write Swift in a demo!


I. Inheritance and rewriting to prevent Rewriting

1.1 base class, does not inherit any class. Swift does not want OC or Java to inherit from the Object class. defines a class, does not inherit any class, this class is the 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. The keyword override must be added. (OC, Java does not need to be added)

Class XiaoHong1: Person1 {override func eat () {super. eat (); // you can use super to call attributes and methods in the parent class println ("xiaohong eat a pig")} var xh = XiaoHong1 () xh. eat ()

1.4 rewrite attributes (storage and computing attributes)

You can use get/set/willSet/didSet to rewrite attributes.
A read-only attribute can be rewritten as a read/write attribute. A read/write attribute cannot be rewritten as a read-only attribute.
That is to say, the rewrite range can only be small --> large (similar to Java)
When a subclass overrides the attributes of a parent class, no matter whether the parent class is a computing or storage attribute, the rewrite process is to override the get/set and so on. The override of the subclass is the format of the computing attribute.

Class Person2 {var name: String {// set {println ("Person2 set")} get {return "Person2"} let age: int = 10 // constant storage attribute var height: Int = 175 // variable storage attribute} class XiaoMing2: Person2 {override var name: String {set {super. name = newValue // set 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, get and set get {println (super. age) return 20 }}override var height: Int {// rewrite observation attribute: inherited constant storage attribute. The observer cannot be added to the read-only calculation attribute. didSet {// note that didSet exists. The println ("didset ---- \ (oldValue)") of get/set cannot appear in willSet )")} willSet {println ("willSet ---- \ (newValue)") }}var xm2 = XiaoMing2 () xm2.name = "XM2" println (xm2.age) xm2.height = 10

1.5 prevent rewriting (final). Same as Java

// You can write final in the class Person3 {final var name = "Person3"} class XiaoMing3 {// override var name... // This will result in an error}

2. Constructor

The constructor in Swift does not return a value (id is returned in OC). Its main task is to ensure that the new instance is correctly initialized before it is used for the first time.

Init (), which can be reloaded

2.1 The default constructor and the constructor with parameters are overloaded.

Class Person4 {var name: String // must be initialized, or initialized in the constructor // default, without the init () parameter () {// No Return Value name = "xuneng"} // self with the init (name: String) parameter {// The parameter name is used as the External Parameter name by default. name = name + "Hello" // same as OC, use self. (this is used in Java)} // contains optional parameters. optional type: It can be null or assigned a value later. initialized to nil var age: Int = 10 init (name: String, age: Int ?) {Self. name = name self. age = age! // Optional parameters must be specified! Can be assigned a value} var p4 = Person4 () // by default, var p4_1 = Person4 (name: "xn4545945") without parentheses ") // The parameter name is used as the External Parameter name var p4_2 = Person4 (name: "neng", age: 10)

2.1 specify the convenience initializer and convenience initializer)

2.1.1 specify the constructor: each class must have at least one to ensure that all values are initialized. (The class will be called Based on the inheritance relationship of the parent class to complete the initialization of the parent class)

// All three constructors in Person4 are specified constructors and all member variables must be initialized.

2.1.2 convenience Constructor (with the convenience keyword): The convenience constructor can be used to specify constructor in the same class or to create an instance with specific input.

Class Person5 {var name: String // must be initialized, or init (name: String) is initialized in the specified constructor {// specify the constructor self. name = name + "Hello"} convenience init (name: String, height: Int) {// constructor. you do not need to initialize all member variables self. init (name: name) println (height)} var p5 = Person5 (name: "xn4545945", height: 175)

2.2 constructor chain (concept): standardizes the call relationship between the constructor and the constructor.

// 1) Rule 1: The specified constructor must call the specified constructor of its parent class. // 2) Rule 2: the constructor must call other constructor called in the same class. // 3) Rule 3: The constructor must end with calling a specified constructor.

Summarize the above three rules in one sentence: specify that the constructor is called up, And the constructor is called horizontally.




2.3 two-stage construction process (concept)

Stage 1: Each storage type attribute sets the initial value by introducing their class constructor.
Stage 2: When each stored property value is determined, it gives each class A Chance To further customize its stored property before the new instance is ready for use.

The use of two-stage constructor makes the constructor safer, and gives full flexibility to each class in the class hierarchy.

The two-segment construction process of Swift is similar to the construction process in Objective-C. The main difference lies in Stage 1. Objective-C assigns 0 or null values (for example, 0 or nil) to each attribute ). Swift's construction process is more flexible. It allows you to set custom initial values and handle situations where some attributes cannot use 0 or nil as the value of the combination method.


2.4 constructor inheritance (concept)

Different from OC, The subclass in Swift does not inherit the constructor of the parent class by default.. (But it will be automatically inherited if the following two conditions are met)
1) if the subclass does not define the specified constructor, it will inherit
2) If the subclass provides the implementation of all the constructors specified by the parent class, the constructor automatically inherits the convenience constructor of the parent class.

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, therefore, the convenience constructor println ("son init")} var son1 = Son () var son2 = Son (name: "xuneng") of the parent class is automatically inherited ") // automatically inherits the convenience constructor of the parent class

2.5 set the default attribute values through closures and functions

// The general format of the closure class SomeClass {let someProperty: Int ={// the entire curly braces indicate a closure return 0} () // The parentheses cannot be lost, indicating that the closure is executed immediately. and return value .}
1) if the value of a storage attribute needs to be customized, you can use the closure or global function class to provide the default value.
2) When a type is created, the closure or function will be called, and their return values will be assigned to this storage property as default values.
3) when the closure is used, other parts of the instance are not initialized and therefore cannot be accessed in the closure: other instance attributes/self attributes/instance methods.

Class Person6 {let name: string = {// you can perform some complex initialization in the closure. let firstName = "xu" let lastName = "neng" return firstName + lastName }()} var p6 = Person6 () println (p6.name)


Iii. deinit

Before a class instance is released, the anti-initialization function is called immediately.
Swift uses ARC to manage the instance memory, which is the same as OC.
Each class has only one anti-initialization function without any parameters and cannot be called actively.
Subclass inherits the anti-initialization function of the parent class(The release sequence is similar to that of Java. Release subclass first --> parent class)
The anti-initialization method can access all attributes of the instance.

Class Person7 {var myMoney: Int init () {myMoney = 10} deinit {myMoney = 0 // variable in the category class can be used. but this sentence is useless. the member variable does not exist because it is destroyed. // you can clear it.} var p: Person7? = Person7 () println (p !. MyMoney) p = nil // optional type can be set to nil // p !. MyMoney // error, set to nil


Refer:

The Swift Programming Language

Apple Dev Center


Reprinted please indicate the source: http://blog.csdn.net/xn4545945



What is the access permission range of the class constructor and destructor in Java?

Java constructor and class name are the same, but the type is not specified.
For example:
Public class Test {
Public Test (){
}
}
Test () is the constructor of the class.

The access permission of the constructor is no different from that of a common function.
Depends on the inheritance relationship between the keywords (public, private, etc.) You add before the function and the class.

Although child classes in java can inherit the members of the parent class, what can be accessed by child classes? Cannot access urgent

Child classes inherit the member variables of the parent class. Child classes inherit the member methods other than the constructor methods. Child classes cannot inherit the constructor methods of the parent class, and child classes can inherit the destructor of the parent class.

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.