Value type and Reference type :
Good link : https://www.codementor.io/blog/value-vs-reference-6fm8x0syje
A value type instance keeps a unique copy of its data, for example, a struct or an enum.
A reference type, shares a single copy of its data, and the type is usually a class.
Value Types
A value type instance is an independent instance and holds its data in its own memory allocation. There are a few different value types: struct, enum, and tuple.
In Swift, Array, String, and Dictionary are all value types.
In value types two variables address in the memory is different.
Struct:
Let’s experiment with structs and prove that they’re value types:
// 1
struct Car {
let brand: String
var model: String
}
// 2
var golf = Car(brand: "Volkswagen", model: "Golf")
// 3
let polo = golf
// 4
golf.model = "Golf 2019"
// 5
print(golf)//Car(brand: "Volkswagen", model: "Golf 2019")
print(polo)//Car(brand: "Volkswagen", model: "Golf")
Even if polo is a copy of golf, the instances remain independent with their own unique data copies.
Enum
To check that enums are value types, add this code to the playground:
// 1
enum Language {
case italian
case english
}
// 2
var italian = Language.italian
// 3
let english = italian
// 4
italian = .english
// 5
print(italian) // english
print(english) // italian
Even if english is a copy of italian, the instances remain independent.
Tuple:
The last value type that we'll explore is tuple. A tuple type is a comma-separated list of zero or more types, enclosed in parentheses. You can access its values using the dot (.) notation followed by the index of the value.
You can also name the elements in a tuple and use the names to access the different values.
Add the following code to the playground:
// 1
var ironMan = ("Tony", "Stark")
// 2
let parent = ironMan
// 3
ironMan.0 = "Alfred"
// 4
print(ironMan) //("Alfred", "Stark")
print(parent) //("Tony", "Stark")
When to Use Value Types:
Use value types when comparing instance data with == makes sense.
== checks if every property of the two instances is the same.
Reference Types:
reference type instances share a single copy of their data, so that every new instance will point to the same address in memory. A typical example is a class, function, or closure.
https://www.codementor.io/blog/value-vs-reference-6fm8x0syje
No comments:
Post a Comment