Value type vs. referenced copy

Source: Internet
Author: User
struct body and enumeration are value typesA value type is given to a variable, or the constant or itself is passed to a function, actually manipulating its copy.

In the previous chapters, we've used a lot of value types. In fact, all of the basic types in Swift are integers (integer), floating-point number (floating-point), Boolean (Booleans), String (string), array (array), and dictionary (dictionaries), which are value types , and are implemented in the background in the form of a structure.

In Swift, all structures and enumerations are value types. This means that their instances, as well as any value-type attributes contained in the instance, are replicated as they are passed in the code.

Consider the following example, which uses the resolution structure in the previous example:
Let HD = Resolution (width:1920, height:1080) var cinema = HD In the above example, a constant named HD is declared with a value of re that is initialized to full HD video resolution (1920 pixel wide, 1080 pixels high) Solution instance.

The example then declares a variable named cinema, whose value is the previously declared HD. Because resolution is a struct, the value of cinema is actually a copy of HD, not HD itself. Although HD and cinema have the same wide (width) and high (height) properties, they are two completely different instances in the background.

Below, in order to meet the needs of the digital cinema Show (2048 pixels wide, 1080 pixels high), the cinema width property needs to be modified as follows:
Cinema.width = 2048 This will show that the width property of the cinema has been changed to 2048:
println ("Cinema is Now" (cinema.width) pixels wide)/output "Cinema is now 2048 pixels wide" However, the width property in the initial HD instance is 1920:
println ("HD is still \ (hd.width) pixels wide")/output "HD is still 1920 pixels wide" When you assign HD to cinema, you are actually storing the value in HD (values ), and then stores the copied data in a new cinema instance. The result is that two completely independent instances happen to contain the same number. Since the two are independent, modifying the width of the cinema to 2048 does not affect the width (width) in HD.

Enumerations also follow the same Code of conduct:
Enum CompassPoint {case North, South, East, West} var currentdirection = compasspoint.west Let remembereddirection = cur Rentdirection currentdirection =. East if rememberdirection = =. West {println ("The remembered direction is still. West ")}//Output" The remembered direction is still. West "In the example above, Remembereddirection is given the value of currentdirection (value), which is actually given a copy of the value. Modifying the value of the currentdirection at the end of the assignment process does not affect the copy of the original value (value) stored by remembereddirection.
class is a reference typeUnlike a value type, a reference type is not copied when it is assigned to a variable, constant, or passed to a function. Therefore, the reference is to an existing instance itself, not to its copy.

Consider the following example, which uses the Videomode class that was previously defined:
Let teneighty = Videomode () teneighty.resolution = HD Teneighty.interlaced = True = "1080i" Teneighty.frame Rate = 25.0 The above example declares a constant named Teneighty that references a new instance of a Videomode class. In the previous example, this video mode was given a copy (HD) of HD resolution (1920*1080). Also set to interleaved (interlaced), named "1080i". Finally, the frame rate is 25.0 frames per second.

The teneighty is then given a new constant named Alsoteneighty, while the frame rate of the alsoteneighty is modified:
Let alsoteneighty = teneighty alsoteneighty.framerate = 30.0 Because classes are reference types, teneight and Alsoteneight actually refer to the same Videomode instance. In other words, they are just two names for the same instance.

Below, by looking at the Framerate property of Teneighty, we find that it correctly shows the new frame rate for the base Videomode instance, with a value of 30.0:
println ("The Framerate property, Teneighty is now \ teneighty.framerate)")/output "The Framerate property of Theeighty is Now 30.0 "Note that Teneighty and Alsoteneighty are declared as constants (constants) rather than variables." However you can still change teneighty.framerate and alsoteneighty.framerate, because these two constants do not change themselves. They do not store this Videomode instance, which is only a reference to the Videomode instance in the background. So, instead of changing the value of a constant, the framerate parameter of the referenced base videomode is changed.
The identity operatorBecause a class is a reference type, it is possible to have multiple constants and variables referencing a class instance in the background. (This is not true for structs and enumerations.) Because they are value types, they are always copied when assigned to constants, variables, or passed to functions. )

It would be helpful if you could determine whether two constants or variables refer to the same class instance. To this end, Swift has built two identical operators:
Equivalent to (= = =) not equivalent to (!==)
The following is the use of these two operators to detect two constants or whether a variable references the same instance:
if teneighty = = alsotentighty {println ("Tentighty and Alsoteneighty refer to the same resolution.")}//Output "instance" Eighty and alsoteneighty refer to the same resolution instance. "Notice the difference between" equivalent "(expressed in three equals, = = =) and" equal to "(indicated by two equals, = =):
"Equivalent to" is a constant or variable referencing the same class instance of the two class type (the class type). "Equals" means that the value of two instances is "equal" or "same", and is judged to conform to the criteria defined by the Class Designer, so this is a more appropriate term than "equal".

assignment and copy behavior of collection (Collection) TypesThe array (array) and dictionary (Dictionary) types in Swift are implemented in the form of structs. However, when an array is given a constant or variable, or is passed to a function or method, its copy behavior is somewhat different from that of the dictionary and other constructs.

The behavior descriptions of the following pairs of arrays and structs are essentially different from those of the Nsarray and Nsdictionary, which are implemented in the form of classes, which are implemented in the form of structures. Nsarray and Nsdictionary instances are always assigned and passed in the form of references to existing instances, rather than copies.
Note: The following is a description of the copy of the array, dictionary, string, and other values. In your code, the copy seems to have actually been created somewhere in the copy behavior. However, in the background of Swift, the actual (actual) copy will only be executed if necessary. Swift manages all of the value copies to ensure optimal performance, so there is no need to avoid assigning values to ensure optimum performance. (actual assignment is optimized by System management) assignment and copy behavior of dictionary typesWhenever a dictionary instance is assigned to a constant or variable, or passed to a function or method, the dictionary is copied when the assignment or call occurs. This procedure is described in detail in the chapter structure and the enumeration is the value type.

If the key (keys) and/or values (values) stored in the dictionary instance are value types (structs or enumerations), they are copied when the assignment or call occurs. Conversely, if keys and/or values (values) are reference types, the copied will be references, not class instances or functions that are referenced by them. The copy behavior of the keys and values of the dictionary is the same as the copy behavior of the properties stored by the structure.

The following example defines a dictionary called ages that stores the names and ages of four people. The ages dictionary is given a new variable called Copiedages, and ages is copied in the process of assigning values. After the assignment is over, ages and Copiedages become two independent dictionaries.
var ages = ["Peter": "Wei": "Anish": "Katya": "Copiedages") var ages = The key (keys) of this dictionary is a string (string) type, and values are integer (Int) type. Both of these types are value types in swift, so when a dictionary is copied, both are copied.

We can verify that the ages dictionary is actually copied by changing the age value in a dictionary to check the corresponding value in another dictionary. If the value of Peter is set to 24 in the Copiedages dictionary, the ages dictionary still returns the value 23 before the modification:
Copiedages["peter"] = println (ages["Peter")//Output "23" assignment and copy behavior of arraysIn Swift, the assignment and copy behavior of an array (Arrays) type is much more complex than the dictionary (Dictionary) type. When manipulating array content, arrays (array) provide performance near the C language, and the copy behavior occurs only when necessary.

If you assign an array instance to a variable or constant, or pass it as a parameter to a function or method call, the contents of the array are not copied when the event occurs. In contrast, arrays share the same sequence of elements. When you modify an element within an array, the result of the modification is displayed in another array.

In the case of an array, the copy behavior occurs only if the operation has the potential to modify the length of the arrays. This behavior includes attaching (appending), inserting (inserting), deleting (removing) or using a range subscript (ranged subscript) to replace the element in this range. The behavior rules of the array contents are the same as the key values in the dictionary only when the array copy does occur, see the assignment and Replication behavior of the chapter [Set (Collection) type] (#assignment_and_copy_behavior_for_collection_ Types

The following example assigns an array of integers (Int) to a variable named a, which is then assigned to variables B and C:
var a = [1, 2, 3]

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: 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.