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