Swift closures, enumerations, classes, and structs

Source: Internet
Author: User
Tags closure

Closures (Closures)
You should not be unfamiliar with code blocks in other languages, and closures in Swift are similar to the block in C,oc. Represents the self-included function code block. Can be passed and used in code.

and the ability to capture and store context variables and constant values, Swift captures related memory operations for you.

The function mentioned in the previous article. It is also a special kind of closure. In detail: A global function is a closed packet that has a name but does not capture whatever value. A nested function is a closure that has a name and is capable of capturing values within the domain. A closure expression is an anonymous closure that is written in lightweight syntax to capture context values.
General syntax for basic syntax expressions and simplified procedures

The above lists five ways to write the same behavior, as well as a scenario for simplifying the method.
Follow closures
If the above closure is written in a way that follows a closure, it behaves as: reversed = sort (names) {$ > $}

Typically, we write a closed-loop expression with multiple lines to the following closure.

For example, the map method of an array can call a closure for each element within a group. Returns a new array.

This captures each value in the numbers array and maps the output to a new strings array.



Value capture
Closures can capture some values in their context, even if the original domain does not already exist.

The above mentioned nested functions are closures that have names that capture values within a domain.

The simplest form of closure in Swift is a nested function.

This defines a nested function makeincrementor, which records a variable runningtotal, which is nested inside the function that captures the value and holds it.



But assuming that the new variable/constant reference to the same function is declared, its runningtotal is not shared


Closures are reference types, and the constants declared above are a reference to the contents of the closure, not the contents of the closure itself.



Enumeration
Swift's enumeration is very flexible, and the value in case can be a string. Character. Integer or float type.

It is also possible to specify that any type of related value is stored in an enumeration member. In Swift, an enumeration is a type (first-class) that supports the attributes (except inheritance) that the class supports. You can define some functions for it to be rich in behavior and so on.


The basic syntax

When we have determined that it is compasspoint, we can use it directly. Value omits the form assignment of the enumeration name.
Switch match

The correlation value was mentioned earlier. We are able to store the relevant values of the arbitrary type to the enumeration member. Take a look at the following example

The barcode enumeration stores some relevant values for the case and can access it using the binding value, such as defining a constant identifier in switch to get the QRCode related value in barcode.


The original value in Swift, the enumeration does not have an implicitly assigned value of 0, 1, like an enumeration in c,objective-c when you do not declare an enumeration value. 2 ... the value is only measured when we assign a value to it. But it is also limited to int. Swift defines a method for it to access the original value Toraw () or to access its enumeration members through Fromraw (value).

Because our enumeration does not have 5 corresponding members, it is nil. But suppose the change is 3. It is green.
What if the enumeration member is a string? Will the value be measured? Of course it's not possible--the compiler will make an error.

A non-integer must be assigned the ability to do enough.

Class and struct
Definitions, instance declarations and properties


Because this does not set the specified constructor of its own definition. So it is possible to initialize an instance directly using the default () method.


The Access setting property uses point syntax, except that, unlike Ojbective--c, Swift agrees to assign a value directly to the sub-attributes of the struct.

Another difference is that the Swift class does not require the. h interface file.

In OC we would like to change the X value of the Rect.origin to assign a new origin to the Rect, and swift to change it directly.


In Swift, structs, enumerations, and classes can be added to the behavior by writing some member functions.

Constructs are slightly different, and structs can provide them with a member constructor.

This is the system's own initiative to provide. And the class is not provided.
Value types and reference types
Structs, enumerations, and classes in addition, the main difference is the type.

Structs and enumerations are value types, and classes are reference types.
A value type means that when an assignment is passed, the system will voluntarily copy a new value for it and pass it to the newly declared variable or constant.

We've changed the width of cinema as soon as the HD is assigned to cinema, but then visit hd.width or the original value 1920. The description simply assigns the HD copy to cinema rather than HD itself.
Reference type This is a new variable or constant that points to the original object, rather than copying the value of the object after it is assigned.

Change the framerate here, and then visit the original variable framerate discovery has also changed. The reason is that they all point to the same heap of memory.



In Swift. The decision reference equality is an identity symbol "= = =". To determine whether to refer to the same instance, without referencing the same instance, or "!==" (not equivalent to) then what is the difference between "= = =" and "= ="? Equivalent to ("= = =") A constant or variable that represents two class types references the same instance.

and "= =" Indicates whether the values of the two instances are equal. Decisions need to follow the criteria defined by the Class Designer.


Because structs are value types. We do not use equivalence to make inferences.



Similarities and differences between classes and structures and their selection
First look at the same point for classes and structs: Defining properties for storing value definition methods used to provide feature definition satellite scripts (subscript) used to access value definition constructors for initializing values and configuring features that extend to add default implementations to conform to the Protocol to provide standard functionality for a class
The difference is that (class) inheritance agrees with a class inheritance and a class's feature type transformation that agrees to examine and interpret a type destructor for a class instance at execution time (the destructor will refer to) agreeing to a class instance releasing no matter what its assigned resource reference count agrees to multiple uses of a class
We usually consider the structure in the following cases: to encapsulate a small amount of related simple data value estimation data passing will be copied instead of referencing the value type attribute in the struct will also be copied without inheriting or inheriting the feature and behavior
Assignment and copy behavior of collection types
The value type and reference type are mentioned above. In Swift, collection-type dictionaries and arrays are implemented in the background as structs, but their situation is slightly special. Although the assignment behavior of the usual value types is achieved through copying, we do not need to be afraid of the performance problems caused by excessive use of memory. Swift manages all of the value copies to ensure optimal performance.
The assignment of dictionaries and the key/value of copy behavior dictionaries. Copy the value if it is a value type. Reference types copy references.

Assignment and copy behavior of arrays
Compared to dictionary arrays, arrays can provide near-C performance when manipulating array content. and ensure that the copy only occurs when necessary.
So when is it necessary? is to change the length of the array, such as append (), insert (), remove () and other functions. The copy of the array will not occur. Does not change when it belongs to a reference pass.


Sometimes we want to make sure that the array is unique, so we can call the Unshare method to make it a unique copy. Force copy uses the copy method. However, copy creates a new copy under no circumstances, and unshare ensures a unique reference.



We can also use "= = =" To determine whether two arrays share the same space or element when deciding whether the array is the same.



Because they are not shared space, the return is false.


The basic knowledge of closing packages, enumerations, structs, and classes is complete.

Errata and discussions are welcome.


Closures, enumerations, classes, and structs for Swift

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.