Pass variable by reference

Some pizzas are divided into four pieces. You eat the first piece and three left. You eat the second one and two left. Now, try to imagine a situation when you eat the first piece and four left. You eat second and still four left.

First eating happens when we pass a reference object or variable by reference. Second eating is default behavior passing value types…

In Swift, two types of variable exist: value and reference. When we pass the value type variable to the function, a new variable will be created in memory and value will be copied. Allocation and copping happen automatically. However, passing a reference type does not create a new variable. The function receives exactly the same instance of a variable from memory and uses it.

pass by value vs pass by refrence gif

Lists below shows which type is value and which is reference

Value types:

-Int, String, Bool, Float

-Enum

-Struct

-Tuple

-Dictionary, Array, Set

Reference types:

-Class

-Function

-Closure

Pass value variable by reference in code

The behavior described before is implicit. We do not need to do anything. But, we can explicitly pass a value type as a reference type and edit it inside the function.

We need to add two things, first put: “&” before variable name passing into the function and second put “inout” before variable type in a function declaration.

var pizzaPieces: Int = 4
print(“Pizza has \(pizzaPieces) before eating.”)
eatByRefenrece(pizzaPieces: &pizzaPieces)
print(“Pizza has \(pizzaPieces) after eating.”)

func eatByRefenrece(pizzaPieces: inout Int) {
    print(“eatByRefenrece, init value: \(pizzaPieces).”)
    pizzaPieces = pizzaPieces –
1
}

Output:

Pizza has 4 before eating.
eatByRefenrece, init value: 4.
Pizza has 3 after eating.