Class - passing by reference

1

Consider the following code ceiling:

class Circle {
    var radius: Double
    init(radius: Double)
    {
        print("I'm initializing a new Circle instance with a radius value of \(radius).")
        self.radius = radius
    }

    deinit {
        print("I'm destroying the Circle instance with a radius value of \(radius).")
    }
}

1 var circle3 = Circle(radius: 42)
2 var referenceToCircle3 = circle3
3 referenceToCircle3.radius
4 circle3 = Circle(radius: 84)

5 referenceToCircle3.radius
6 circle3.radius

Since these are classes, the passage is by reference, correct? That is, since referenceToCircle3 is equal to circle3 , both will have the same address in memory, so always the same value will be stored there. So why does referenceToCircle3 (line 5) remain with the same value even when circle3 had its value changed (line 4)?

    
asked by anonymous 28.02.2016 / 15:05

1 answer

0
  

Since it is about classes, the passage is by reference, correct?

Answer: Correct.

Classes in Swift are Reference Types while Structs are Value Types . (I can explain this difference in another question)

  

Then why does referenceToCircle3 (line 5) remain with the same value even when circle3 had its value changed (line 4)?

When you invoke Circle(radius: 84) it means that a new object of type Circle will be created with another memory address and passed into the circle3 variable, so if you want change the reference value for an object directly into it.

isdifferentfrom:

    
29.02.2016 / 21:45