SLN SLN - 6 months ago 9
Swift Question

Create a Value/Constant from a value by reference, and then what's the difference?

I kind of know what is by reference and by value in general, but for some points I feel very confused with details

Let's define the class

Person
and initialize a Constant and a Variable from it and then pass them around the code

class Person{
var ID: Int
var name: String

init (ID: Int, name: String){
self.ID = ID
self.name = name
}
}

var bornVar = Person(ID: 101, name: "me") // initialize a variable
let Tom = bornVar // pass the varialbe to a constant
var Tim = Tom // pass the variable to a variable


let bornLet = Person(ID: 102, name: "I") // initialize a constant
let Kim = bornLet // pass the constant to another constant
var Jim = Kim // pass the constant to a variable


Question: If someone ask me: what is the difference between
Tom
,
Tim
,
Kim
and
Jim
, I can't give out a clear answer. Very appreciate if someone can help me with this

Answer
var bornVar = Person(ID: 101, name: "me")  //  initialize a variable
let Tom = bornVar // assigning the ref of `bornVar` which is having person object reference and you can't assign the any other object to `Tom`
var Tim = Tom // assigning the reference of person object using `Tom` 


let bornLet = Person(ID: 102, name: "I") //  initialize a constant
let Kim = bornLet // pass the constant to another constant
var Jim = Kim  // pass the constant to a variable

You created here two objects bornVar and bornLet with parameterzied init which are pointing to Person

Tom is a property which reference we can't change and it is pointing to bornVar which is a having person object reference

Tim is a property which is pointing to bornVar and you can change it reference

in the same way

Kim is a property which reference we can't change and it is pointing to bornLet which is a having person object reference

Jim is a property which is pointing to bornLet and you can change it reference

look at this example

class MyObject : Equatable {
let a : Int, b : String
init(a: Int, b: String) { self.a = a; self.b = b }
}
// ...

let a = MyObject(a: 10, b: "foo")
let b = a
let c = MyObject(a: 10, b: "foo")

a == b    // true; 'a' and 'b' are equal in value
a === b   // true; 'a' and 'b' point to the same instance

a == c    // true; 'a' and 'b' are equal in value
a === c   // false; 'a' and 'c' are different instances