Structures and Enumerations Are Value Types
- A value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.
- In fact, all of the basic types in Swift-integers, floating-point numbers, Booleans, strings, arrays and dictionaries-are value types, and are implemented as structures behind the scenes.
- All structures and enumerations are value types in Swift. This meas that any structure and enumeration instances you create-and any value types they have as properties-are always copied when they are passed around in your code.
An Example to describe the Essence
struct Resolution {
var width = 0
var hetight = 0
}
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
cinema.width = 2048
print("\(hd.widht)")
print("\(cinema.widht)")
- When cinema was given the current value of hd, the values stored in hd were copied into the new cinema instance. The end result was two completely separate instances that contained the same numeric values. However, because they are separate instances, setting the width of cinema to 2048 doesn’t affect the width stored in hd, as shown in the figure below:
The Same Behavior applies to Enumerations:
enum CompassPoint {
case north, south, east, west
mutating func turnNorth() {
self = .north
}
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection.turnNorth()
print("\(currentDirection)")
print("\(rememberedDirection)")
- When rememberedDirection is assigned the value of currentDirection, it’s acutally set to a copy of that value. Changing the value of currentDirection thereafter doesn’t affect the copy of the original value that was stored in rememberedDirection.
Choosing Between Structures and Classes
- Structures and classes are good choices for storing data and modeling behavior in your apps, but their similarities can make it difficult to choose one over the other.
- Consider the following recommendations to help choose which option makes sence when adding a new data type to your app.
- Using structures makes it easier to reason about a portion of your code without needing to consider the whole state of your app. Because structures are value types-unlike classes-local changes to a structure aren’t visible to the rest of your app unless you intentionally communicate those changes as part of the flow of your app. As a result, you can look at a section of code and be more confident that changes to instances in that secion will be made explicitly, rather than being made invisibly from a tangentially related function call.
|
请发表评论