Swift Study Notes: class and Structure

Source: Internet
Author: User

I. Similarities and Differences between classes and structures

Classes and structures are similar. They can all be:
1. Define attributes that can be assigned values;
2. Define functional methods
3. Define the subscript and use the subscript syntax
4. Define the initialization method to set the initial status
5. scalability in the original Implementation Method
Provides basic functions for a specific category based on the protocol
1. The class also has some features that the structure does not have:
2. Inheritance of Classes
3. Real-time type conversion for class instances
4. Analyze a class instance to release space

5. Reference count. A class instance can have multiple references.


1. Definition syntax

struct Name{    let firstName = ""    let secondName = ""}class Student{    var name = Name()    var height = 0.0    var score = 0}let a = Student()

As shown in the code, we define a struct Name and a class Student. Note the following when defining struct and classes:
Note:
① Based on writing specifications, the first letter of the definition of struct and classes should be capitalized.
② In the definition of struct and class, each attribute must have a default value. Otherwise, the compiler reports an error.

2. Access attributes and Structure Type Initialization

Let name1 = Name (firstName: "", secondName: "") let a = Student () a. name = name1; a. height = 185

In the above Code, we first Initialize an instance name1 of the Name struct, then initialize the instance of the Student class, and assign values to this instance. Focuses on the following aspects:
Important:
① The initialization of a struct can specify the initial value through the attribute name just like calling an external function.
② Attribute access. Add "." And the attribute name after the instance to access the attribute.

Note:
① Different from the structure, the class instance cannot use the member initialization method. class initialization will be detailed later.
② Unlike Objective-C, Swift can directly set sub-attributes of a structure attribute.


II, The structure and enumeration type are numerical values.

The value type means that when it is assigned to a constant or variable, or passed as a parameter to a function, it completely copies a new value instead of simply changing the reference object.

Struct Name {var firstName = "" var secondName = ""} var a = Name (firstName: "small", secondName: "stupid wolf") var B = aa. firstName = "" println (B. firstName) // output: Small
As shown in the preceding example, the structure type value assignment creates a complete value. The original object change will not affect the value assignment object.

3. Class is the reference type

Different from the structure type, the class belongs to the reference type, and the class value assignment only applies the reference value assignment.
Struct Name {var firstName = "" var secondName = ""} class Student {var name = Name () var height = 0 var score = 0} let a = Student () let B = aa. score = 98 println (B. score) // output: 98
As shown in the preceding example, if a is assigned a value to B, the attribute of a is changed, and the attribute of B is changed. Because a and B are two pointers, they both point to the same address.

Iv. feature operations
Determines whether two objects point to the same instance address. Use = and! = To judge
Let a = Student () let B = aif a = B {println ("a = B")} else {println ("! = B ")} // Output a = B
As shown in the code above, a and B point to the same instance and a = B is output.
Note:
① This is not to judge whether they belong to the same class. If B is another instance of the Student class, it will not be equal.
② You cannot use =. The Compiler reports an error.

V, How to select a class or structure
You can select a class or structure in the code to implement the required code block and complete the corresponding functions. However, the structure instance transmits a value, while the class instance transmits a reference. For different tasks, we should consider the different data structure and functional requirements to select different instances.
Generally, when one or more of the following conditions are met, You should create a structure:
1. structure is mainly used to encapsulate some simple data values
2. When assigning values or passing values, you may want the encapsulated data to be assigned values instead of being referenced.
3. All properties stored in the structure are also numerical.
4. structure does not need to be inherited by another type or complete other behaviors
In other cases, the class is a better choice. That is to say, data is generally defined as a class.

VI, Assignment and copying of set types
Unlike Objective-C, arrays Array and Dictionary in Swift are implemented using structures. Let's take a look at their specific differences.

1.Assignment and copying of dictionaries

Var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya ": 19] var copiedAges = agesages ["Wei"] = 0 println (ages) // output: [Anish: 65, Wei: 0, Peter: 23, Katya: 19] println (copiedAges) // output: [Anish: 65, Wei: 35, Peter: 23, Katya: 19]
Because the dictionary is of the numerical type, the value is fully assigned during the value assignment.
If the key values in the dictionary are numeric (structure or enumeration), they will be copied when assigned. On the contrary, if it is a reference type (class or function), the reference itself will be copied, not the class instance or function itself. The replication method and structure of the dictionary are the same.


2.Array assignment and copying operations
Compared with the Dictionary type, Array assignment and copying operations are more complex. The Array type is similar to that in C language. The value of the Array is completely copied only when necessary.
If an array is assigned to a constant or variable, or is passed to a function as a parameter, copying does not happen when values are assigned or called. The two arrays will share a sequence of elements. If you modify one of them, the other will also change.
For arrays, copying only happens when you perform an operation that may modify the length of an array. Includes splicing, adding or removing elements. When the copy operation actually occurs, it will be the same as the assignment of the dictionary and the copy operation.

Var a = [1, 2, 3] var B = aa [0] = 5 println (a) // output: [5, 2, 3] println (B) // output: [5, 2, 3]. append (4) println (a) // output: [5, 2, 3, 4] println (B) // output: [5, 2, 3]
As shown in the example above:
1. assign a value to B. If only the value of the array is changed and the length is not changed, the array will not be copied, and B will change with.
2. If the length is changed, it will be copied. B will be a new array and will not change with.
3. Array independence
If you do not want two variables to share an array when assigning values to an array, you can use the unshare keyword to make the array independent.

Var a = [1, 2, 3] var B = aa. unshare () B [0] = 5 println (a) // output: [1, 2, 3] println (B) // output: [5, 2, 3]
Important:
① When calling the. unshare () method, the array will be copied, and then let a point to the copy array. Other pointers also point to the original object

4. Determine whether two arrays point to the same Array address
To determine whether two arrays direct to the same Array address, you can use ==and! =

var a = [1,2,3]var b = aif a === b{ }
Note:
If unshare is called for a or B. They no longer point to the same Array address.
5. Force array copy
If you want to copy the entire array to a new array, you can use the copy method.
var a = [1,2,3]var b = a.copy()
Note:
① At this time, arrays a and B are two irrelevant arrays, and changing the value will not affect the other side.
② If you are not sure whether the array you need is independent, simply use unshare. The copy method, whether it is independent or not, will be completely copied once, even if the array is unshare.










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.