Value types versus reference types
As a refresher, let's quickly cover the difference between value and reference types. Value types hold values and copy content on assignment or when they are passed to methods as a parameter.
let avg1: Double = 98.1 var avg2 = avg1 avg2 += 1.2 // -> 99.3
In the preceding example, avg2
copies the value of avg1
, and is free to change its value without affecting the value of avg1
. Reference types, on the other hand, share content by default. Changing one of the variables will change the underlying value that each reference shares.
let dateComponents1 = NSDateComponents() dateComponents1.setValue(10, forComponent: .Day) dateComponents1.day // => 10 var dateComponents2 = dateComponents1 dateComponents2.setValue(2, forComponent: .Day) dateComponents1.day // => 2 dateComponents2.day // => 2
In this example, we use the reference type NSDateComponents
to create dateComponents1
and set...