Value vs. Reference Types Flashcards
let p3 = Point(x: 4, y: 2) → p3 is created with a struct of variables x and y. Can we change the x or y for p3?
We cannot change the x and y of p3 despite them being variables because p3 is a constant
var p4 = AnotherPoint(x: 3, y: 2) is created with a struct of constants x and y. Can we change the x or y for p4?
We can’t change the x or y for p4 either because x and y are constants.
BUT you can assign p4 to a different AnotherPoint by doing p4 = AnotherPoint(x: 43, y: 6)
Why does our function need mutating? ‘
struct Point {
var x: Double
var y: Double
mutating func moveLeft(steps: Double) { x -= steps } }
without mutating, this will not work because we have to remember that value types are immutable.
When dealing with classes, what happens to the anotherRobot.model for the example below?
var someRobot = Robot(model: "T1999") var anotherRobot = someRobot
someRobot.model = “T2000”
Both of these become T2000 because these are both reference types. they are pulling this information from memory
class Robot { var model: String
init(model:String) { self.model = model } }
If we create an instance of Robot that is a constant, can we change the model of it? See below
let thirdRobot = Robot(model: "T3000") thirdRobot.model = "T4000"
This does change the model to T4000 because the variable doesn’t actually contain the actual object but a reference of the object in memory.
How does the mutating keyword change the behavior of a struct’s instance method?
It indicates that the method will modify the struct’s values allowing the compiler to create a copy of the struct
TF: Assigning a value type to a variable means you can change the value assigned to the variable, but not the value itself.
True
TF: When we assign an instance of a reference type to a constant, the thing that’s constant isn’t the object, it’s the reference to the object.
True
TF: We can modify properties in a reference type even when it is assigned to a constant
True
In reference types, final class implements the same behavior as which keyword?
Static
How do we prevent a reference type from being subclassed?
Use final keyword
TF: Modifying a reference type contained within a value type creates a new copy of the value type
False - Since the reference type is directly modified in memory, the value type is not mutated or copied
How does the class keyword differ from static when creating type methods?
Indicated that the method can be overridden in subclasses.
If we have a class, final class Calculator {}, can I subclass it?
No, final classes cannot be changed.
If we have a method in a class, and we want to alter it in a subclass, what do we have to type before changing the method?
Override, because you are changing it.