Swift struct and class, Swift struct

Source: Internet
Author: User

Swift struct and class, Swift struct
In a process-oriented programming language (such as C language), struct is used a lot, but after object-oriented, such as in C ++ and Objective-C, struct is rarely used. This is because struct can do things, and classes can be replaced completely.
The Swift language attaches great importance to struct and uses struct as an important means to achieve object-oriented development. Struct in Swift differs greatly from struct in C ++ and Objective-C. struct in C ++ and Objective-C can only define a group of relevant member variables, the struct in Swift can not only define member variables (attributes), but also Member methods. Therefore, we can regard struct as a lightweight class.
Classes and structs in Swift are very similar. They all have object-oriented features such as definitions and usage attributes, methods, subscripts, and constructors, but struct does not have inheritance, it also does not have the ability to force type conversion during running, to use the destructor, and to use the reference meter.
I. Class and struct Definition
The syntax for defining classes and struct in Swift is also very similar. We can use class keywords to define classes and struct keywords to define struct. Their syntax format is as follows:
Class name {
Define class members
}
Struct name {
Define struct members
}
In terms of syntax format, the definition of classes and struct in Swift is more similar to Java syntax, and the interface part and implementation part do not need to be put into different files like C ++ and Objective-C.
The naming rules for class names and struct names are the same as those for enumeration types. Here is an example:
Class Employee {// defines the Employee class
Var no: Int = 0 // define the employee ID attribute
Var name: String = "" // defines employee name attributes
Var job: String? // Define work attributes
Var salary: Double = 0 // defines salary attributes


Var dept: Department? // Define the attributes of the Department
}


Struct Department {// define the Department struct
Var no: Int = 0 // define the Department ID attribute
Var name: String = "" // define the Department name attribute
}
Employee is the class we define, and Department is the struct we define. In Employee and Department, we only define some attributes. We will introduce the attributes in the next chapter.
There is a correlation between the Employee and the Department. The attribute dept of the Department where the Employee is located is associated with the Department. Their class diagram is shown in.
 
The following statements can be used for instantiation:
Var emp = Employee ()
Var dept = Department ()
Employee () and Department () are constructors that call them for instantiation. We will introduce the constructors in section 14.1.
After the prompt is instantiated, the memory space will be opened up. emp and dept are called "instances", but only the "instances" of class instantiation can be called "objects ". In fact, not only structures and classes can be instantiated, but enumeration, function types, and closures can also be called Instantiation and the results can also be called "instances ", but it cannot be called "object ".
Ii. Repeat the value type and reference type
Data types can be divided into value type and reference type, which are determined by the value assignment or parameter transfer method. The value type is to create a copy when assigning values or passing parameters to the function, and pass the copy over, so that the original data will not be affected during the function call process. The reference type is to pass its own data when assigning values or passing parameters to the function. In this way, the original data will be affected during the function call process.
Among the many data types, we only need to remember that only the class is the reference type, and all other types are the value type. Even if the struct is very similar to the class, it is also a value type. Value types include integer, floating point, Boolean, String, tuples, set, and enumeration.
The reference type in Swift is the same as that in Java, and the class in Java is also the reference type. If you have no Java experience, you can understand the reference type as the pointer type in C, C ++, and Objective-C, however, you do not need to add a star number (*) before the referenced type variable or constant (*).
Here is an example:

Var dept = Department () ① dept. no = 10dept. name = "Sales" ② var emp = Employee () ③ emp. no = 1000emp. name = "Martin" emp. job = "Salesman" emp. salary = 1250emp. dept = dept ④ func updateDept (dept: Department) {⑤ dept. name = "Research" ⑥} println ("before Department update: \ (dept. name) ") 7updatedept (dept) Partition println (" updated Department: \ (dept. name) ") using func updateEmp (emp: Employee) {using emp. job = "Clerk" Clerk} println ("before updating Employee: \ (emp. job) ") ⑫ updateEmp (emp) ⑬ println (" after the Employee is updated: \ (emp. job) ") Submit


Code ① ~ (2) create a Department struct instance and set its properties. Code ③ ~ (4) Create an Employee class instance and set its attributes.
To test whether the struct is a value type, we define the updateDept function in the Code in line ⑤. Its parameter is the Department struct instance. Line 6 code dept. name = "Research" is used to change the dept instance. Then, print the Department name attributes before the update in Row 7, update the Department name attributes in the first row, and print the updated Department name attributes in the second row. If the results are the same before and after the update, the struct type is the value type, and the reverse type is the reference type. In fact, the sixth line of code will have a compilation error. The error message is as follows.
Playground execution failed: error: <REPL >:34: 15: error: cannot assign to 'name' in 'dept'
Dept. name = "Research"
~~~~~~~~~ ^
The error message "dept. name =" Research "indicates that the dept struct cannot be modified because it is a value type. In fact, there is another way to transfer value type parameters to reference types. In chapter 9th, we introduced the input and output type parameters declared using inout. here we need to modify the code:
Func updateDept (inout dept: Department ){
Dept. name = "Research"
}


Println ("Department before update: \ (dept. name )")
UpdateDept (& dept)
Println ("Department updated: \ (dept. name )")
We should not only declare the parameter as inout, but also add the & symbol before using the instance. The output result is as follows:
Before Department update: Sales
After the Department is updated: Research
In contrast, the nth line of code defines the updateEmp function, and its parameter is an instance of the Employee class. We do not need to declare the parameter as the inout type. There is no compilation error when modifying emp in the nth line. This indicates that the Employee class is of the reference type and does not need to add the & symbol before the variable during the call. For details, refer to the line of the Code. The output result is as follows:
Before Employee update: Salesman
After the Employee is updated: Clerk
The result shows that the class is a reference class.
Iii. Comparison of reference types
In Chapter 4th, we introduced the basic operators and mentioned constant equals (=) and non-constant equals (! =) Relational operators. === Used to compare whether two references are the same instance ,! = It is the opposite. It can only be used to reference the type, that is, the instance of the class.
Here is an example:
Var emp1 = Employee () ① emp1.no = 1000emp1. name = "Martin" emp1.job = "Salesman" emp1.salary = 1250var emp2 = Employee () ② emp2.no = 1000emp2. name = "Martin" emp2.job = "Salesman" emp2.salary = 1250if emp1 = emp2 ③ {println ("emp1 = emp2 ")} if emp1 = emp1 ④ {println ("emp1 = emp1")} var dept1 = Department () ⑤ dept1.no = 10dept1. name = "Sales" var dept2 = Department () ⑥ dept2.no = 10dept2. name = "Sales" if dept1 = dept2 // compilation failed 7 {println ("dept1 = dept2 ")}


The preceding Code creates two Employee instances, namely, emp1 and emp2, respectively, row ① and row ②. In line ③ of the Code, compare whether the references of emp1 and emp2 are an instance. We can see that the comparison result is False, that is, the references of emp1 and emp2 are not an instance. Even if the content is identical, the result is False, and the comparison result of Line 4 is True. If we use = for comparison, what will happen? The Code is as follows:
If emp1 = emp2
{
Println ("emp1 = emp2 ")
}
The answer is the following compilation errors. = The comparison requires that the types of the two instances (class, struct, enumeration, etc.) must be rewritten in this type = Operator to define equal rules. The same error occurs in the code at line 7.
Playground execution failed: error: <REPL >:42: 9: error: cocould not find an overload for '=' that accepts the supplied arguments
If emp1 = emp2
~~~~~ ^ ~~~~~~
The dept1 and dept2 Department instances are created respectively in line 5 and line 6 of the Code. Use = in line 7 of the Code to compare whether the values dept1 and dept2 are equal. Not only can they not be compared, but compilation errors also occur, which has been explained above.
If we compare dept1 and dept2 with constant equals =, what will happen? The Code is as follows:
If dept1 = dept2
{
Println ("dept1 = dept2 ")
}

We found a compilation error. ===Cannot compare the value type, while the Department struct is a value type. Therefore, you cannot use === for comparison.




For more information, please refer to the first domestic Swift book "Swift development guide" for discussion. Website: http://www.51work6.com/swift.phpwelcome to the swifttechnology discussion group: 362298.pdf

Welcome to Zhijie iOS public classroom Platform



What is the struct type declared as a swift language variable?

Although I have never seen swift, it seems that a instantiates the object of A class. Therefore, a can access the attributes of Class. B inherits from A, and B has the public attributes of Class.

Class and struct

No parameter-free constructor for the Structure

Structure cannot be inherited

The structure is a value type, and the class is a reference type.

Structure is more efficient in terms of data parameters, and the cost of simple array applications is very low

Class has more advantages in method operations and is the best choice when multiple levels of abstraction

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.