Class - pass by reference

Asked

Viewed 234 times

1

Consider the following code Techo:

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 it is about classes, the passage is by reference, correct? That is, how referenceToCircle3 is equal to circle3, both will have the same address in memory, Tuesday always the same value stored there. Then why referenceToCircle3 (line 5) remains at the same value even when the circle3 had its value changed (line 4)?

1 answer

0

Since these are classes, the passage is by reference, correct?

Answer: Correct.

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


So why referenceToCircle3 (line 5) remains at the same value even when circle3 had its value changed (line 4)?

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


inserir a descrição da imagem aqui

is different from:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.