Swift closure, enumeration, class and struct

Source: Internet
Author: User
Closure (closures)
If you have used other languages, you should be familiar with the code block. The closure in SWIFT is similar to the block in C and OC. Indicates the self-contained function code block, which can be passed and used in the code. In addition, it can capture and store context variables and constant values. Swift will capture memory operations for you.

The function mentioned in the previous article is also a special closure. Specifically, a global function has a name but does not capture any value. Nested functions are closures with names and can capture values in the domain. Closure expressions are anonymous closures that use lightweight syntax to capture context values.
General syntax and simplified process of basic syntax expressions

The five ways to write the same behavior are listed above, which also indicate the applicable scenarios of the simplified method.
Trailing Closure
If the closure above is written using the trailing closure, It is shown as: reversed = sort (names) {$0> $1}

We usually write closure expressions with multiple rows into the trailing closure. For example, the map method of array can call the closure once for each element in the logarithm group to return a new array.

Each value in the numbers array is captured and the output is mapped to a new strings array.

Value capture
A closure can capture some values in its context even if the original domain does not exist. As mentioned above, nested functions have closures with names that can capture values in the domain. The simplest form of closure in SWIFT is nested functions.

Here we define a nested function makeincrementor, which records a variable runningtotal. The nested function can capture this value and keep it.

However, if a new variable/constant reference of the same function is declared, its runningtotal is not shared.


A closure is a reference type. The constants declared above point to a reference of the closure content, rather than the closure content itself.

Enumeration
Swift enumeration is very flexible. The value in case can be string, character, integer or floating point type. You can also specify any type of values to store in the enumerated members. In swift, enumeration is of the first-class type. It supports the features supported by classes (except inheritance). You can define some functions for them to enrich their behavior.
Basic syntax

When we have determined that it is compasspoint, we can directly use. Value to omit the enumeration name.
Switch matching

As mentioned above, we can store any type of values to enumeration members. Let's look at the example below.

We have stored some case-related values for the barcode enumeration and can access it by binding values, for example, a constant identifier is defined in the switch to obtain the qrcode value in barcode.
Original values in swift, enumeration does not implicitly assign values 0, 1, 2 if you do not declare an enumeration value in C, objective-c... only when we assign a value to it will we guess its value, but it is also limited to int. Swift defines a method for it to access the original value toraw () or to access its enumerated members through fromraw (value.

Because our enumeration does not have 5 members, it is nil. If it is 3, it is green.
What if the enumerated member is a string? Will it be guessed? Of course it is unlikely.-The Compiler reports an error.

A non-integer must be assigned a value.

Class and struct
Definition, instance declaration and attributes


Because no custom constructor is set here, you can use the default method () to initialize an instance.
The dot syntax is used to access the set attributes. However, unlike Ojbective -- C, swift allows direct assignment of values to the child attributes of the struct. The other difference is that the. h interface file is not required for the swift class.

In oC, if we want to modify the X value of rect. Origin, we often need to assign a new origin to rect, While Swift can directly modify it.
In swift, struct, enumeration, and classes can be added to a struct by writing some member functions. The constructor is slightly different. The constructor can provide one-by-one member constructor for the constructor.

This is automatically provided by the system, while the class is not provided.
Value Type and reference type
Struct. Another major difference between enumeration and classes is type. Struct and enumeration are value types, while classes are reference types.
Value Type indicates that when a value is transferred, the system automatically copies a new value for it and passes it to the new declared variable or constant.

We note that the width of cinema is modified immediately after the HD value is assigned to cinema, but then access HD. width is still the original value of 1920. it means that the copy of HD is assigned to cinema, not HD itself.
Reference Type: this refers to directing a new variable or constant to the original object, instead of assigning values after copying the object value.

Here, the framerate is modified, and the original variable's framerate is accessed. The reason is that they all point to the same heap memory.

In swift, it is determined that the reference is equal to a constant sign "=" to determine whether to reference the same instance. If the same instance is not referenced, it is "! = "(Not equivalent to) So what is the difference between" = "and" =? It is equivalent to ("=") indicating that constants or variables of two class types reference the same instance. "=" Indicates whether the values of the two instances are equal. The judgment must comply with the criteria defined by the class designer.
Since struct is of the value type, we do not use the equivalent value for judgment.

Similarities and differences between classes and struct
First, let's take a look at the similarities between classes and struct: Define attributes to store the value definition method to provide a feature definition ancillary script (subindex) the access value definition constructor is used to initialize values and configurations. By extension, the default implemented functions comply with the Protocol to provide standard functions for a certain type of feature.
The difference is: (class) Inheritance allows one class to inherit the feature type conversion of another class. It allows you to check and interpret the type deconstruct of one class instance at runtime (as mentioned in the destructor) allows a class instance to release any of its allocated resource reference count. Allows multiple use of a class.
We usually consider struct in the following situations: it is used to encapsulate a small amount of related simple data values. It is expected that data transmission will be copied, not the value type attribute in the referenced struct. It will also be copied without inheritance or inheritance features and behaviors.
Assignment and copying of set types
The value type and reference type are described above. In swift, the dictionary and array of the collection type are implemented by struct in the background, but their situation is somewhat special. Although the assignment of value types is usually implemented through copying, we do not need to be afraid of performance problems caused by excessive memory usage. Swift will manage all value copies to ensure optimal performance.
In the key/value of the dictionary, if it is of the value type, the value is copied. If it is of the reference type, the reference is copied.

Assignment and copying of Arrays
The array is much more complex than the dictionary array. When operating the array content, the array can provide performance close to that of the C language, and ensure that the copy only occurs when necessary.
So when is it necessary? Is to change the length of the array, such as calling the append (), insert (), remove () and other functions, the copy of the array will occur, if not changed, it is a reference transfer.


Sometimes we want to ensure the uniqueness of the array, then we can call the unshare method to make it a unique copy. The copy method is used for forced copy. However, copy creates a new copy under any circumstances, while unshare ensures unique reference.

When determining whether the array is consistent, we can also use "=" to determine whether the two arrays share the same space or element.

Because they all do not share space, false is returned.


The basics of closures, enumerations, structs, and classes are all explained. Surveys and discussions are welcome.
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.