Learn Swift note finishing from 0 (iii)

Source: Internet
Author: User

This is followed by the following in the previous post:

--swift The related properties in

Store Properties

The properties in Swift are divided into storage properties and computed properties, which are data members in OBJECTIVE-C, calculated properties do not store data, but can be returned by calculating other properties. Storage properties can store data in constant attributes (defined with a keyword let) and variable attributes (defined with key Var).
Storage Attribute Concepts:
We used the previous attribute, employee class, and department struct. Their class diagrams are as follows, and the Employee's Departmental attribute dept is associated with department.

We can specify default values when defining storage properties, as shown in the example code:
Class Employee {
Let No:int = 0
var name:string = ""
var job:string?
var salary:double = 0
var dept:department?
}
struct Department {
Let No:int = 0
var name:string = ""
}
Let emp = Employee ()
emp.no = 100//Compile Error: Modify constant property, program will compile error
Let dept = Department ()
Dept.name = "SALES"//Compile Error: Dept is a value type and the value type cannot be modified, even if its property name is a variable property and cannot be modified
Let EMP1 = Employee ()
Emp1.name = "Tony"

Calculated properties

The computed property itself does not store the data, but instead computes it from other storage properties.

The computed property provides a getter (accessor) to get the value, and an optional setter (set accessor) to indirectly set the value of another property or variable. The syntax format for the computed attribute is as follows:

Object-oriented type type name {

Store Properties

......

Var computed property Name: property data type {

get {

Return computed property value

}

Set (new property value) {

......

}

}

}

It is troublesome to define computed properties, note the alignment of the following braces.

Let's look at an example first:

Import Foundation

Class Employee {

var no:int = 0

var firstname:string = "Tony"//Storage properties

var lastname:string = "Guan"//Storage properties

var job:string?

var salary:double = 0

Lazy var dept:department = Department ()

var fullname:string {//computed properties

get {

return FirstName + "." + lastName//return stitching Results

}

Set (Newfullname) {//store pass in parameter values

var name =newfullname.componentsseparatedbystring (".")

FirstName = name[0]

LastName = name[1]

}

}

}

struct Department {

Let No:int = 0

var name:string = ""

}

var emp = Employee ()

Print (Emp.fullname)//Take out property values

Emp.fullname = "Tom.guan"//Assigning a value to a property

Print (Emp.fullname)

Read-only computed properties:

Computed properties can be only getter accessors, without setter accessors, which are read-only computed properties. Specifying a computed property not only does not have to write the setter accessor, but the get{} code can also be omitted. Compared to the previous section, the code is greatly reduced. Modify the previous section as a read-only computed property with the following code:

Class Employee {

var no:int = 0

var firstname:string = "Tony"

var lastname:string = "Guan"

var job:string?

var salary:double = 0

Lazy var dept:department = Department ()

var fullname:string {//compact setter accessor

return FirstName + "." + LastName

}

}

struct Department {

Let No:int = 0

var name:string = ""

}

var emp = Employee ()

Print (Emp.fullname)

A read-only computed property cannot be assigned a value, and the following statement is incorrect.

Emp.fullname = "Tom.guan"

Attribute Observer

To listen for changes in the properties, SWIFT provides a property observer. Property observers can listen for changes in storage properties, even if the values are the same before and after the change.
There are two main attributes of the Observer:
· Willset: The observer was called before the modification.
· Didset: The Observer is called immediately after the modification.
The syntax format for a property observer is as follows:
Object-oriented type type name {
...
var Store property: Property Data type = Initialize value {
Willset (new value) {//define Willset Observer. The "new value" is a parameter passed to the Willset Observer, which holds the new value that will replace the original property
...
}
Didset (old value) {//Definition Didset observer. The old value is the argument passed to the Didset Observer, which holds the old value replaced by the new attribute.
...
}
}
}
The syntax format of the attribute observer is more chaotic than the computed attribute.
Attribute observers can be used in classes and structs, and cannot be used in enumerations.
The sample code is as follows:
Class Employee {
var no:int = 0
var name:string = "Tony" {
Willset (Newnamevalue) {//defines the Willset observer for the Name property, Newnamevalue is the parameter name that we assign to pass the new value
Print ("Employee name new value: \ (newnamevalue)")
}
Didset (Oldnamevalue) {//defines the Didset observer for the Name property, Oldnamevalue is the parameter name that we assign to pass the old value
Print ("Employee name old value: \ (oldnamevalue)")
}
}
var job:string?
var salary:double = 0
var dept:department?
}

struct Department {
var no:int = 10 {
willset{//Willset Observer that defines the No property, note that there are no parameters declared here, but we can use it inside the observer newvalue
Print ("Department number new value: \ (newvalue)")
}
didset{//Didset Observer that defines the No property, note that there is no parameter declared here, but we can use it inside the observer oldvalue
Print ("department number old value: \ (oldValue)")
}
}
var name:string = "the"
}

var emp = Employee ()
emp.no = 100
Emp.name = "Smith"

var dept = Department ()
dept.no = 30
The result of the above code operation is as follows:
Employee Name new value: Smith
Employee name old value: Tony
Department number new value: 30
Department number old value: 10

Static properties

Let me first design a class: There is an account (bank accounts) class, assuming it has 3 attributes: Amount (account amount), interestrate (interest rate), and owner (account name).

Of these 3 attributes, amount and owner will vary from one account to another, and the contents of each account are different, and the interestrate of all accounts are the same.

The amount and owner properties are related to the account entity, called instance properties. The InterestRate attribute is independent of the individual, or shared by all account individuals, which is called a static property or type attribute.

Object-oriented types (structs, enumerations, and classes) can all define static properties, and their syntax formats are as follows:

struct struct Name {//define struct body, can define static storage property and static computed property in struct

static VAR (or let) store property = "XXX"

...

Static Var computed property name: property data type {

get {

Return computed property value

}

Set (new property value) {

...

}

}

}

Enum enum Name {///define enumeration in which an instance store property cannot be defined, but you can define a static storage property, or you can define a static computed property

static VAR (or let) store property = "XXX"

...

Static Var computed property name: property data type {

get {

Return computed property value

}

Set (new property value) {

...

}

}

}

Class class Name {//define classes in which you can define not only instance store properties, but also static storage properties

static VAR (or let) store property = "XXX"

...

Class (or Static) var computed property name: property data type {

get {

Return computed property value

}

Set (new property value) {

...

}

}

}

struct static computed properties can also be read-only, with the following syntax:

Static Var computed property name: property data type {

Return computed property value

}

Look at an account struct static Property Example:

struct Account {//Define account structure body

var amount:double = 0.0//Account Amount

var owner:string = ""//Account name

static var interestrate:double = 0.0668//define the stored property interestrate interest rate

static Var staticprop:double {//define statically computed properties Staticprop

return interestrate * 1_000_000

}

var instanceprop:double {//Define instance calculation properties Instanceprop

Return Account.interestrate * Amount

}

}

accessing static properties

Print (Account.staticprop)

var myAccount = account ()

accessing instance Properties

Myaccount.amount = 1_000_000

accessing static properties

Print (Myaccount.instanceprop)

--swift Subscript

var studentlist:string[] = ["Zhang San", "John Doe", "Harry"]
Studentlist[0] = "Zhuge Liang"

var studentdictionary = [102: "Zhang San", 105: "John Doe", 109: "Harry"]
STUDENTDICTIONARY[110] = "Zhao Liu"

When accessing arrays and dictionaries, you can use subscript access. Where the subscript of an array is an integer type index, the subscript of the dictionary is its "key".

The subscript in Swift is equivalent to indexed properties in Java and Indexers in C #.

The syntax format for subscript access is as follows:

Object-oriented type type name {

Other properties

...

Subscript (parameter: parameter data type), return value data type {

get {

return value

}

Set (new property value) {

...

}

}

}

The subscript also has getter and setter accessors similar to the computed properties.

The getter accessor is a method that returns the result of the calculation using the return statement at the end.

The setter accessor "new property value" is the value to assign to the property. The declaration of the parameter can be omitted, and the system assigns a default parameter, NewValue.

There is no two-dimensional array available in Swift, only one-dimensional array. You can customize a two-dimensional array type, and then access its elements through two subscript parameters, formally similar to the two-dimensional array of C language.

-- default constructor

Instances of structs and classes call a special Init method, called a constructor, during construction. The constructor does not have a return value and can be overloaded. In the case of multiple constructor overloads, the runtime can invoke the appropriate constructor based on its external parameter name or parameter list.

Structs and classes call a constructor during construction, and even if no constructors are written, the compiler provides a default constructor. Here's the sample code:

Class Rectangle {

var width:double = 0.0

var height:double = 0.0

}

var rect = Rectangle ()//Create instance and invoke default constructor init ()
Rect.width = 320.0
Rect.height = 480.0
Print ("Rectangle: \ (rect.width) x \ (rect.height)")

Rectangle () means that a method is called, which is the default constructor, Init ().

In fact, the constructor is omitted during the definition of rectangle, which is equivalent to the following code:

Class Rectangle {

var width:double = 0.0

var height:double = 0.0

Init () {

}

}

If rectangle is a struct, it is defined as follows:

struct Rectangle {

var width:double = 0.0

var height:double = 0.0

}

The default constructor for struct rectangle is different from the default constructor for class rectangle, which is equivalent to the following code:

struct Rectangle {

var width:double = 0.0

var height:double = 0.0

Init () {

}

Init (width:double, height:double) {//parameter-constructor

Self.width = width

Self.height = height

}

}

Which constructor to invoke is determined by the parameter name and the type of argument passed.

-- Constructors and storage property initialization

The main function of the constructor is to initialize the instance, which includes initializing the storage properties and other initialization. In a rectangle class or struct, if you initialize the storage property width and height in the constructor, you do not need to initialize it when you define them.

The rectangle class code is as follows:

Class Rectangle {

var width:double

var height:double

Init () {

width = 0.0

Height = 0.0

}

}

If the stored property is not initialized in the constructor and is not initialized at the time of definition, a compilation error occurs.
Constructors can also initialize a constant store property
Local parameter names in constructors can be used directly as external parameter names

To enhance the readability of the program, methods and functions in Swift can use the names of external parameters. External parameter names can also be used in constructors. External parameter names in constructors are more meaningful than normal methods and functions, because constructor naming is init, and if there is more than one constructor in a type, we can differentiate calls to different constructors by different external parameter names.

-- Constructor Overloading

Constructors can also be overloaded as a special method.
In swift, constructors can be multiple, and their argument lists and return values can be different, and these constructors form overloads.

To reduce code duplication between multiple constructors, you can define a constructor by calling other constructors to complete the partial construction of the instance, called the constructor proxy. Constructor proxies are used differently in structs and classes, and the constructor proxies in structs are introduced first.
The example in the previous section is modified as follows:
struct Rectangle {
var width:double
var height:double
Init (width:double, height:double) {
Self.width = width
Self.height = height
}
Init (W width:double,h height:double) {
Self.width = width
Self.height = height
}
Init (length:double) {//called Self.init statement
Self.init (W:length, H:length)
}
Init () {//Call the Self.init statement
Self.init (width:640.0, height:940.0)
}
}
var rectc1 = Rectangle (width:320.0, height:480.0)
Print ("Rectangle: \ (rectc1.width) x\ (rectc1.height)")
var rectc2 = Rectangle (w:320.0, h:480.0)
Print ("Rectangle: \ (rectc2.width) x\ (rectc2.height)")
var rectc3 = Rectangle (length:500.0)
Print ("Rectangle 3:\ (rectc3.width) x\ (rectc3.height)")
var rectc4 = Rectangle ()
Print ("Rectangle 4:\ (rectc4.width) x\ (rectc4.height)")
Declare rectangle as a struct type, which also has 4 constructor overloads.
This calls the other constructors of the current type in the same type through the Self.init statement, and the other constructors are called constructor proxies.
class constructor Horizontal Proxy
Because classes have inheritance relationships, class constructor proxies are more complex and are divided into horizontal and upward proxies.
· A horizontal proxy is similar to a struct type constructor proxy, which occurs inside the same class, which is called a convenience constructor (convenience initializers).
· An up-agent occurs in the case of an inheritance in which the parent class constructor is called to initialize the stored property of the parent class, which is called the specified constructor (designated initializers).

Constructor Call rules

You can use the constructor proxy in a constructor to help complete some of the construction work. Class constructor proxies are divided into horizontal and upward proxies, which can only occur inside the same class, and this constructor is called a convenience constructor. An up-agent occurs in the case of inheritance, in which the parent class constructor is called to initialize the stored property of the parent class, which is called the specified constructor, during the child class construction.

Examples of person and student classes:
Class Person {
var name:string
var age:int
Func description (), String {
Return "\ (name) age is: \ (aged)"
}
Convenience init () {//convenience constructor
Self.init (Name: "Tony")
Self.age = 18
}
Convenience init (name:string) {//convenience constructor
Self.init (Name:name, age:18)
}
Init (name:string, Age:int) {//Specify constructor
Self.name = Name
Self.age = Age
}
}
Class Student:person {
var school:string
Init (name:string, Age:int, school:string) {//Specify constructors
Self.school = School
Super.init (Name:name, Age:age)
}
Convenience override Init (name:string, Age:int) {//convenience constructor
Self.init (Name:name, Age:age,school: "Tsinghua University")
}
}
Let student = student ()
Print ("Student: \ (student.description ())")
Calls between constructors form a chain of constructor functions.
Swift restricts the rules for proxy calls between constructors to have 3, as shown below.
1. Specifies that the constructor must call the specified constructor of its immediate parent class. Visible from the diagram, the ④ number in student specifies that the constructor calls the ③ number in the person specified by the constructor.
2. The convenience constructor must call other constructors defined in the same class. As seen from the diagram, the ⑤ in student facilitates constructors to call the ④ in the same class to facilitate constructors, and the ① number in person facilitates constructors by calling the ② number in the same class.
3. The convenience constructor must end with the invocation of a specified constructor function. From the diagram, the ⑤ number in student facilitates the constructor to call the ④ number in the same class to specify the constructor, and the ② number in the person facilitates the constructor to call the ③ number in the same class to specify the constructor.

-- Inheritance of Classes

Inheritance in Swift can only occur on a class and cannot occur on enumerations and structs. A class can inherit a method, property, subscript, and other characteristics of another class, and when a class inherits from another class, the inheriting class is called a subclass, and the inherited class is called the parent class (or superclass). After the subclass inherits the parent class, you can override the properties of the parent class's methods, attributes, subscripts, and so on.
To understand inheritance, look at a scenario where an object-oriented programmer, Xiao Zhao, needs to describe and process personal information during programming, so he defines the class person as follows:
Class Person {
var name:string
var age:int
Func description (), String {
Return "\ (name) age is: \ (aged)"
}
Init () {
Name = ""
Age = 1
}
}
A week later, Xiao Zhao met a new need to describe and process student information, so he defined a new class student, as follows:
Class Student {
var name:string
var age:int
var school:string
Func description (), String {
Return "\ (name) age is: \ (aged)"
}
Init () {
School = ""
Name = ""
Age = 8
}
}
Many people will think that Xiao Zhao's approach can understand and believe that this is feasible, but the problem is that student and person two class structure is too close, the latter is only more than the former attribute school, but to repeat the definition of all the other content, it is "not reconciled." Swift provides a mechanism to solve similar problems, that is, the inheritance of classes, the code is as follows:
Class Student:person {
var school:string
Override Init () {
School = ""
Super.init ()
Age = 8
}
}
The student class inherits all the characteristics in the person class, and the person class after ":" is the parent class. A class in Swift can have no parent class, such as a person class, and there is no ":" When defined, and this is a base class without a parent class.
also override Init () is a subclass that overrides the parent class constructor.
In general, a subclass can inherit only one parent class, which is called single inheritance, but in some cases a subclass may have multiple different parent classes, which is called multiple inheritance. In Swift, the inheritance of a class can only be single-inheritance. Multiple inheritance can be implemented by complying with multiple protocols. In other words, in swift, a class can inherit only one parent class, but it is possible to follow multiple protocols.

-- Constructor Inheritance

There are two sources of child class constructors in Swift: writing and inheriting from the parent class. Not all constructors of the parent class can inherit, and constructors that inherit from the parent class are conditional, as shown below.
· Condition 1: If the subclass does not define any of the specified constructors, it automatically inherits the specified constructors for all the parent classes.
· Condition 2: If the subclass provides all of the parent class to specify the implementation of the constructor, whether inherited through condition 1, or by writing it yourself, it will automatically inherit all the convenience constructors of the parent class. (example ignored)

-- Overriding Properties

Overrides instance properties. We can override the attributes inherited from the parent class in the subclass, with the attributes of the instance and the static attributes, and they differ in the implementation.
Overrides of instance properties can override getter and setter accessors on the one hand, and can override property watchers on the other.
Calculating static properties requires getter and setter accessors, and storage properties are not required. After inheriting the parent class, the subclass can also override the parent class's storage properties and computed properties through getter and setter accessors.
From property overrides, the subclass itself does not store data, and the data is stored in the parent class's stored property.

Overrides a static property.

A static property definition in a class uses the class or static keyword, but which is used to see if the property is overridden in a subclass.

Class-Modified properties can be overridden, and the static keyword cannot be overridden. (example ignored)

This is the basic note that I am learning swift to organize, hope to give more just learn iOS developer to bring help, here bloggers thank you very much for your support!

Please refer to my next blog post for more information. And then in the ongoing update ...

Learn Swift note finishing from 0 (iii)

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.