Swift's distinctive struct and class

Source: Internet
Author: User
Tags instance method

When it comes to structs and classes, or that sentence, as long as the small partners who have been in touch with programming are not unfamiliar with the two. However, the struct and class in Swift also have a very bright feature. The function of the struct becomes more powerful and the class becomes more flexible. Not only can you define a property in a struct, but you can also define a function in it, which is more like the attribute of class. However, struct is a struct after all, it does not support inheritance and other class-specific properties. Today this blog is serious to engage in Swift's struct and class.

Of course, this blog is a relatively basic, but the basic thing is the important thing, not much to say, walk.

I. struct (struct)

struct, plainly, is a set of variables that have a uniform name. In swift, not only can we declare variables in a struct and set default values for variables, but we can add corresponding functions in a struct. Next we will create a point struct with two attribute x and Y coordinates, and an initial value of 0 for the x and Y coordinates. There are two methods, one is the display method, which is responsible for the coordinates of the output point, and there is also a SetPoint method, which is responsible for setting the coordinate point. Then we'll go to the struct to declare the variable and invoke the method.

1. Definition of struct type

Using the struct keyword to declare our struct type, the struct type name is mypoint, where coordinate x, y is the variable, and its initial value is 0. And added a Setmypoint () method and a display () method for our structure.

By the code snippet above you may notice a mutating keyword in front of the Setmypoint () method keyword func. In a struct, a function that defaults (without adding the mutating keyword) has only read-only access to properties in a struct. If you add a mutating, the function holds read and write permissions on the property.

2. Declaration of struct-type variables and use of struct-body functions

Next we use the "mypoint" struct type above to create a struct type variable. Because the (x, Y) value has an initial value, you do not need to specify an initial value for the struct variable when it is initialized. The use of struct types is similar to class usage. MyPoint () is similar to a class's constructor. After we declare the variables and allocate the memory space, we print the values of x, Y and we can see X, the initial value of y is 0. The following are the specific examples:

We can invoke the Setmypoint () method of access to read and write to change the value of the property in the struct variable, and the bottom is to assign the coordinates (10.0,20.0) to the MyPoint variable, as shown below.

In addition to the methods described above to assign values to properties in struct variables, we can also assign values to their properties through constructors. That is, assigning an initial value to a variable when it allocates memory space is similar to the constructor of the class. The exact way is shown in the code snippet in the slice:

    The structure is the first to talk about here, the following is the more important part: class

  

Two. Classes (Class)

How can Swift be a modern object-oriented programming language without classes? For the class in OBJC, please refer to one of my previous blogs, "talking about object-oriented" in Objective-c, which discusses object-oriented things in objective-c. Today we talk about the classes in swift, although the language is not, but the class is still the same. This section of this blog focuses on the way in which the syntax in the Swift class has been used and does not make too many representations about object-oriented thinking, because our focus is on swift programming, not object-oriented programming. Good ~ into this part of the subject.

1. Creation of classes and constructors

For the sake of simplicity is also the principle of easy-to-follow, next will be the above MyPoint structure type used in the form of classes to achieve. The simple grammatical view of the two is similar. The code snippet below is modified in the MYPOINT structure above. Change to the lower MyPoint class made two changes, the 1th is to change the struct keyword to class keyword,

Below is the use of the MyPoint class, although there is no constructor in the above class, a default parameterless constructor is automatically generated. As shown below, the invocation is the default parameterless constructor for the instantiation of the class. Because we specify an initial value for the property in the class (that is, the characteristics of the class) when the class is defined, the initial value is displayed when the value is printed.

When you define a class, you do not define other constructors for it, and if you call that undefined constructor, then you are wrong, and the compiler will give you an error, as shown here:

Next we are going to create a constructor for our MyPoint () class. Unlike other modern programming languages such as C + +, C#,java, and so on, Swift's constructor is not a function with the same name as the class name, but rather uses a specific function name, init (), to create its constructor. Below is the constructor of our MyPoint class, and the function name is, of course, init. In the parameter list of the constructor, we can specify a default value for the parameter, although underneath is just a constructor, but the constructor is combined with the default value in his formal parameter list, which is a beautiful combination of punches, which is often used in a dusty and handy.

Assigning a default value to the parameter list of a constructor eliminates the hassle of overloading the constructor. A constructor is added above and a default value is specified for each parameter, and below is a different invocation method, which should be overloaded with 4 constructors in C + + to achieve the effect. The swift language shows that it is a bright, spirits heart. The specific invocation is as follows:

2. Assignment and comparison of objects

In Swift, it is also permissible to assign the value of a variable of a class to another variable by assigning an operator (=). But one thing to understand is that if the value of class variable A is assigned to the class variable B, then the variables a and B point to the same area of memory. If the value in the instance variable in a is modified, the value in instance B is also modified. To better express this idea, let's take a look at the assignment of the object in a schematic diagram. The specific schematic is as follows:

Above is the principle, below is the verification. Let's declare two variables a, B. Assign a space for an instance to a, and assign a to B. Then you change the value of a and observe the property changes in B. The following are the specific examples:

If you want to determine whether two variables point to the same instance, then we need to use the identity operator (= = =). Below is to determine whether a and B point to the same memory space, the specific code is as follows:

3. Lazy loading of properties (lazy)

In Swift's class, some properties are initialized when the class is initialized. If the initialization of some properties is very time-consuming, then in this case we can initialize the time-consuming property declared as lazy-loaded. is to add the Lazy keyword when the attribute is declared. Variables modified by the Lazy keyword are allocated only when they are used. Below is an example of lazy.

In the example below, in addition to the MyPoint class, we also need to define a mycycle class. In the Mycycle class, use the MyPoint class. The MyPoint property in the Mycycle class is lazy-loaded, depending on the code, as shown below:

(1) Define the Mycycle class, in the Mycycle class, define a MyPoint class variable with a property of lazy. As shown below:

(2) The next step is to use mycycle, declare a variable of type mycycle, and assign it an instance of type Mycycle. As the following example shows, when the Mycycle () constructor is called, the Point property in the Mycycle class is not initialized, and point is nil at the moment. This reduces the time that the mycycle is initialized.

(3) The lazy attribute point is initialized when the Mycycle instance object is using the Point property, and below is the code snippet for the Mycycle instance variable that invokes the A-property, and then it is clear that it is not nil. As shown below:

4. Calculated attribute (Count property)

The attribute of the computed property is also not in objective-c. What is a computed property, in a nutshell: The value of a computed property can be computed by the value of another property, and it can be used to calculate the value of other properties when assigning a value to a computed property. Perhaps it is more difficult to say, understanding may be some difficulties, then a small example to understand the calculation of the property is going on.

Below we create a class named money that has two properties in the Money class, one for the store property (normal property) named CNY (for renminbi) and another for the calculated attribute named USD (for USD). The value of CNY is computed by the value of USD in the set method of the USD calculation property, and the value of USD is calculated from CNY in the Get method of the USD computed property and returned. The specific code snippet for the Money class is as follows:

There is no difference between the use of a computed property and the stored property, and below is the code snippet for the money instance to invoke its storage properties and computed properties, as shown in the resulting output. The code snippet below is simple, but you have a taste of the product slowly. The first part, which is the first assignment to USD, is calculated immediately when the value of USD is assigned. When we assign a value to CNY, the value of USD is not immediately computed because the Get method is called only when USD is used, and the value of USD is calculated based on the value of the CNY. See the code snippet below for specific results:

    

5. Attribute observation

What does attribute observation do for you? To put it bluntly, the attribute observer is to observe the assignment of the property, the attribute observer includes Willset () and Didset, Willset is called when the property is to be assigned, Didset is called after the property is assigned, and for these two attribute observation functions, an instance is at a glance. As the following example shows, when Willset is called, the value of the property attribute is also the default value, but when Didset executes, it is already assigned a value.

6. Example Methods and class methods

In OBJC, the class method is decorated by +, and the instance method is decorated by the-number. There is no + or-no modifier in Swift's method, but there is one more class when declaring a method in Swift. There is nothing special about ordinary methods, and the Declaration and definition of a class method requires the class keyword to be added before the keyword func. An instance method and a class method are defined in the mytestclass below, and the invocation method is given as follows:

The content of today's blog is here first, the next blog will involve some classes of inheritance and the methods and properties in the class access to other things about the class.

Swift's distinctive struct and class

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.