- Mastering macOS Programming
- Stuart Grimshaw
- 282字
- 2021-07-02 22:54:16
Value and reference types
The basic data types of Swift, such as Int, Double, and Bool, are said to be value types. This means that, when passing a value to a function (including assignment of variables and constants), it is copied into its new location:
var x1 = 1
var y1 = x1
y1 = 2
x1 == 1 // true
However, this concept extends to String, Array, Dictionary, and many other objects that, in some languages, notably Objective C, are passed by reference. Passing by reference means that we pass a pointer to the actual object itself, as an argument, rather than just copy its value:
var referenceObject1 = someValue
var referenceObject2 = referenceObject1
referenceObject2 = someNewValue
These two variables now point to the same instance.
While this pattern is frequently desirable, it does leave a lot of variables sharing the same data--if you change one, you change the others. And that's a great source of bugs.
So, in Swift, we have many more value types than reference types. This even extends to data structures and classes, which come in two flavors; struct and class (see Structs, classes, and other data structures in this chapter). This is part of a widespread trend in programming toward copying immutable objects rather than sharing mutable ones.
Swift is pretty smart about managing all this copying. An object of value type is not, in fact, copied until the copy is changed, for example, and there are a lot of other tricks going on under the hood, none of which you need to take care of yourself.
So remember, structs, Strings, and Arrays are passed by value, just the same as Int, Double, and Bool.