On the classes, structures and initialization operations in Swift

Source: Internet
Author: User

First of all, let's declare a class

class Parent {   // declares a property    var p1:string = "abc"       // declares a method     func m () {        print ("parent m")    }    / /    final func n () {            }}

Then we new a parent class (note that there is no new in Swift, if you want to make a new one, call the class directly)

var par = Parent ()

Calling methods and properties of parent

PAR.M ()//On the console display is the parent   m par.p1//displayed in the console is 5

Well, this is the definition of the class we use and the invocation of the method (property).

Next, we're going to learn about the inheritance of the parent class in Swift.

We'll take the parent of the above as the Father class, we first write a subclass to inherit the parent class, if you want to

When overriding a property or method of a parent class, be sure to add an override keyword

classchild:parent {//When overriding a property or method of a parent class, be sure to add an override keyword//because the parent class attribute defined here is a storage property, if you want to rewrite the parent class, you will turn the P1 into a computational//Properties    Overridevar p1:string{Get {                    return "DASDF"                }                Set {                }    }     Overridefunc m () {print ("Child M")    }

Calling the properties of a child class

var par1:parent = Child1 () print ("dfdfd\ (PAR1.P1)")//  It shows dfdfddasdf.

If you want to inherit a parent class, you must first note the following requirements

1. Override the storage property of the parent class to add an observer to it (new feature)

2. You can change it to a calculated attribute (but not to reduce its functionality)

3. The parent class is read-only (get, or let), and subclasses cannot add observers

****************************

Classes and structs are a common and flexible construct that people use to build code. In order to implement various functions in classes and structs, we must define attributes and add methods in strict accordance with the syntax rules specified for constants, variables, and functions.

Unlike other programming languages, Swift does not require you to create separate interfaces and implementation files for your custom classes and structs. All you have to do is define a class or struct in a single file, and the system will automatically generate external interfaces for other code.

Note: Typically an instance of a class is called an object. However, in swift, classes and structs are more closely related than in other languages, and most of the features discussed in this chapter can be used on classes and structs. Therefore, we will primarily use instances rather than objects.

Next, let's talk about the similarities and differences between class and struts in Swift.

Classes and structs in Swift have a lot in common. The Common place is:

Defining properties for storing values

Define methods to provide functionality

Define subscript for accessing values through the following banner method

Defining initializers for generating initialization values

Extended to add functionality to the default implementation

Compliance with protocols to provide standard functionality for a class

Compared to structs, classes have the following additional functions:

Inheritance allows one class to inherit the characteristics of another class

Type conversions allow you to check and interpret the type of a class instance at run time

Canceling the initializer allows a class instance to free any resources it has been assigned

Reference count allows multiple references to a class

*******************************

Initialization: an instance of a type (enum, struct, Class) has a sequence of processes in the construction process

Primary purpose of initialization: assigning values to internal storage properties

Structure: If you do not add the initialization yourself, the default init and memberwise init will be added automatically


//A struct is defined here,structPoint3 {var x:int=1var y:int=2 //Here we need to explain a few points of a constructor (init)//1. In general, to write a very full constructor, you can initialize all the members (a specific initializer)//2. You can write multiple init, but you must call a very full constructorInit (xx:int) {self.init (xx:xx,yy:1)} init (yy:int) {//x = 1//y = yySelf.init (XX:1, Yy:yy)//Self is not to be omitted. } //write a full constructor to initialize all the membersInit (Xx:int, Yy:int) {x=xx y=yy}}

In the above we have mentioned the difference between struct and class, class does not add an initialization by itself, it must add its own

Gold Rule 1: All storage properties must have values (two method assignments) after instantiation

1. Special (specific) initializer designated Initiliazer assignment, which assigns values to all storage properties of this class

2. Assign a value directly after the variable (constant)

class's dedicated initializer:

1. You can have multiple

2. Cannot invoke each other, each responsible for implementing the initialization of all the storage properties of this class

3. Responsible for handling initialization of inherited storage properties.

3.1 Trust Others, so the expression is to call the parent class of the specific initializer (cannot

Invoke the convenience initializer of the parent class)

Convenient initializers:

1. You can have multiple

2. You can invoke other convenient initializers, or you can call a specific initializer for this class

3. It must eventually be called the specific initializer of this class

//effect: 1. Assigning values to all storage properties of this classclassAA {var m:int var n:int
Specific initializer init (mm:int,nn:int) {m=mm N=nn} init () {m=111N= A //This will result in an error indicating that the specific init cannot be called from each other//so it's recommended that you actually write only one specific initializer per class//self.init (mm:111,nn:222) } //a convenient initializer requires the invocation of a dedicated initializer (either directly or indirectly)convenience init (mm:int) {self.init (mm:mm,nn:1)} convenience init (nn:int) {//self.init (Mm:1,nn:2)self.init (MM:NN)}}

And then, let's look at a piece of code, how to implement the initialization of the parent class through subclasses.

classParent {var i:int=1   //var m:string?//only types that can be nil have default valuesvar m:int init (m:int) {self.m=m}}classChild :P arent {var n:int init (n:int) {//Stage OneSELF.N = n//finish your own work first.Super.init (M:1)//It 's called the parent class .//Stage Twom =2//If you're not satisfied with the parent, do it yourself.    }}

Well, this is my view of Swift in the Class,struts, write bad, please forgive me oh, thank you

On the classes, structures and initialization operations in Swift

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.