Swift Structures and classes

Source: Internet
Author: User

In process-oriented programming languages such as C, structs are used much more, but after object-oriented, such as in C + + and objective-c, structs are rarely used. This is because the structure can do things, the class can be replaced completely.
The swift language attaches great importance to the structure and the structure as an important means to realize object-oriented. Structs in swift differ greatly from those in C + + and objective-c, and structs in C + + and objective-c can only define a set of related member variables, and the struct in swift not only defines member variables (attributes), but also defines member methods. Therefore, we can think of a struct as a lightweight class.
Classes and structs in Swift are very similar in that they have object-oriented features such as defining and using properties, methods, subscripts, and constructors, but structs are not inherited or have the ability to enforce type conversions at run time, use destructors, and use reference gauges.
I. Definitions of classes and structures
The syntax for classes and struct-body definitions in Swift is very similar. We can use the Class keyword to define classes, use struct keywords to define structs, and their syntax is as follows:
Class Name {
Defining members of a class
}
struct struct body name {
Define the members of the struct body
}
From the syntax format, the definition of classes and structs in Swift is more like Java syntax, and there is no need to put the interface and implementation parts in different files like C + + and objective-c.
The naming conventions for class names, struct names, and enumeration types are the same. Let's look at an example:
Class Employee {//Define employee class
var No:int = 0//Define Employee number attribute
var name:string = ""//define Employee Name attribute
var job:string?//defining work Properties
var salary:double = 0//Define pay attributes


var dept:department? Define the Department property in which you are
}


struct Department {//define departmental structure body
var no:int = 0//Defines the department number attribute
var name:string = ""//define Department name attribute
}
Employee is the class we define, and department is the structure we define. In both employee and department, we have defined only a few attributes. The contents of the property are described in the next chapter.
Employee and Department are related, and the attribute dept of the employee's department is associated with department, as shown in the class diagram.

We can instantiate through the following statements:
var emp = Employee ()
var dept = Department ()
Employee () and department () are instantiated by the constructor that invokes them, and we will describe the constructors in section 14.1.
Tip The memory space is created after the instantiation, and the EMP and dept are called "instances", but only "instances" of the class instantiation can be called "objects". In fact, not only structs and classes can be instantiated, but the process of enumerating, function types, and closures opening up memory space can also be called instantiation, and the result can also be called an "instance", but not an "object".
Second, talk about value types and reference types
Data types can be divided into: value types and reference types, which are determined by the assignment or parameter passing method. A value type is one that creates a copy and passes the copy over when the parameter is assigned or passed to the function, so that the original data is not affected during the invocation of the function. A reference type is the passing of its own data when assigning or passing arguments to a function, which affects the original data during the invocation of the function.
Among the many data types, we just need to remember that only the class is a reference type, and all other types are value types. Even if the struct is very similar to a class, it is a value type. Value types also include integral, floating-point, Boolean, String, tuple, collection, and enumeration.
The reference type in Swift is the same as the reference type in Java, and the class in Java is also a reference type. If you do not have Java experience, you can interpret reference types as pointer types in C, C + +, and objective-c languages, except that you do not need to precede the reference type variable or constant with an asterisk (*).
Let's look at an example:

[HTML]View Plaincopy
  1. var dept = Department () ①
  2. dept.no = Ten
  3. Dept.name = "Sales" ②
  4. var emp = Employee () ③
  5. emp.no = +
  6. Emp.name = "Martin"
  7. Emp.job = "Salesman"
  8. Emp.salary = 1250
  9. emp.dept = Dept④
  10. Func updatedept (dept:department) {⑤
  11. dept.name = "⑥ "
  12. }
  13. println ("Department before update: \ (dept.name)") ⑦
  14. Updatedept (Dept) ⑧
  15. println ("department after update: \ (dept.name)") ⑨
  16. Func updateemp (emp:employee) {⑩
  17. emp.job = "Clerk"?
  18. }
  19. println ("Before Employee update: \ (emp.job)")?
  20. Updateemp (EMP)?
  21. println ("Employee Updated: \ (emp.job)")?



The above Code section ①~② creates an instance of the department struct and sets its properties. The Code section ③~④ creates an employee class instance and sets its properties.
To test whether a struct is a value type, we define the Updatedept function in the ⑤ line code whose argument is an instance of the department struct body. Line ⑥ Code dept.name = "study" is a change dept instance. Then, in line ⑦, the department Name property before the update is printed, updated in line ⑧, and the updated department Name property is printed on line ⑨. If the results are consistent before and after the update, then the struct is a value type and vice versa is a reference type. In fact, the ⑥ line code will have a compile error, the error message is as follows.
Playground execution Failed:error: <repl>:34:15:error:cannot assign to ' name ' in ' dept '
Dept.name = "the"
~~~~~~~~~ ^
This error indicates that dept.name = "The" is not assignable, which means that the dept struct cannot be modified because it is a value type. In fact, there is another way to make value type parameters can be passed by reference type, we introduced in the 9th chapter using the InOut declaration of input and output type parameters, here need to modify the code:
Func updatedept (inout dept:department) {
Dept.name = "the"
}


println ("Department before update: \ (dept.name)")
Updatedept (&dept)
println ("department after update: \ (dept.name)")
We will not only declare the parameter as InOut, but also add the & symbol before using the instance. The result of this modification is as follows:
Department before update: Sales
Department after update:
In contrast, the ⑩ code is the definition of the Updateemp function whose arguments are instances of the employee class, and we do not need to declare the parameters as InOut types. Modifying the EMP in the first line does not compile errors, which means that the employee class is a reference type and does not need to add the & symbol before the variable at the time of the call, see Line of code. The output results are as follows:
Before Employee update: salesman
After employee update: Clerk
This result again shows that the class is a reference class.
Iii. Comparison of reference types
In the 4th chapter we introduce the basic operators, which refer to the constant equals (= = =) and the non-constant Equals (!===) relational operators. = = = To compare whether two references are the same instance,!=== is the opposite, it can only be used for reference types, that is, instances of classes.
Let's look at an example:

[HTML]View Plaincopy
  1. var emp1 = Employee () ①
  2. emp1.no = +
  3. Emp1.name = "Martin"
  4. Emp1.job = "Salesman"
  5. Emp1.salary = 1250
  6. var emp2 = Employee () ②
  7. emp2.no = +
  8. Emp2.name = "Martin"
  9. Emp2.job = "Salesman"
  10. Emp2.salary = 1250
  11. If emp1 = = = Emp2③
  12. {
  13. println ("emp1 = = = EMP2")
  14. }
  15. If emp1 = = = Emp1④
  16. {
  17. println ("emp1 = = = Emp1")
  18. }
  19. var dept1 = Department () ⑤
  20. dept1.no = Ten
  21. Dept1.name = "Sales"
  22. var dept2 = Department () ⑥
  23. dept2.no = Ten
  24. Dept2.name = "Sales"
  25. If dept1 = = DEPT2//compile failed ⑦
  26. {
  27. println ("dept1 = = = Dept2")
  28. }



The above code, line ① and line ②, respectively, created EMP1 and EMP2 two employee instances. In the Code section ③, compare the EMP1 and emp2 two references as an instance. You can see that the comparison result is false, that is, EMP1 and emp2 two references are not an instance, that is, their contents are exactly the same, and the result is false, and the result of the comparison of line ④ is true. If we compare by = =, what will the result be? The code is as follows:
if emp1 = = EMP2
{
println ("emp1 = = = EMP2")
}
The answer is a compilation error like the following. = = Comparison requires that the type of two instances (class, struct, enum, and so on) must be overridden in the type = = operator to define an equality rule. The same error will also occur in line ⑦ code.
Playground execution Failed:error: <repl>:42:9: Error:could not find a overload for ' = = ' that accepts the Supplie D arguments
if emp1 = = EMP2
~~~~~^~~~~~~
The code line ⑤ and line ⑥ respectively create DEPT1 and DEPT2 two department instances. using = = In the code line ⑦ to compare dept1 and dept2 two values for equality, not only to compare, but also to compile errors, which have been explained above.
What would happen if we used constant equals = = = to compare dept1 and dept2? The code is as follows:
if dept1 = = = Dept2
{
println ("dept1 = = = Dept2")
}

We found that there would be compile errors. = = = The value type cannot be compared, and the department struct is a value type, so the = = = Comparison cannot be used.

For more information, please visit the first Swift book "Swift Development Guide" book Exchange discussion website: http://www.51work6.com/swift.php Welcome to join Swift Technical discussion group: 362298485

Welcome to Luxgen iOS Classroom public Platform

Swift Structures and classes

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.