Reference Types

• While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References".

• In this method, the address of actual variables in the calling function are copied into the dummy variables of the called function.

• Reference types consist of shared instances that can be passed around and referenced by multiple variables. This is best illustrated with an example.

class car {

var working = true

}

The above class represents a car and whether or not the car is been working. Create a new instance of your car class by adding the following:

let honda = car()

This simply points to a location in memory that stores honda. To add another object to hold a reference to the same honda, add the following:

let bmw = honda

Because honda is a reference to a memory address, bmw points to the exact same data in memory.

bmw.working = false

After this step, for cheking further add following lines

print("is honda working? ", honda)

print("is bmw working? ", bmw)

this will print:

is honda working? false

is bmw working? false

Changing one named instance affects the other since they both reference the same object.

With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.

Value Types

• While calling a function, we pass values of variables to it. Such functions are known as “Call By Values”.

• In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.

var a = 10

var b = a

b += 10

a // 10

b // 20

What is going to values for a and b? Clearly, a equals 10 and b equals 20. If you’d declared them as reference types instead, both a and b would equal 20 since both would point to the same memory address.

Let me compare both with same examples for clear visulization.

struct Car {

var working = false

}

var honda = Car()

var bmw = cat

bmw.wasFed = true

honda.wasFed // false

bmw.wasFed // true

• With this method, using addresses we would have an access to the actual variables and hence we would be able to manipulate them.