Reference types

In Swift, a structure is an immutable value. A class, on the other hand, is a mutable reference.

What does this mean? Because classes are reference types, a variable of a class type does not store an actual instance, but a reference to a location in memory that stores the instance. If you were to create a simple Person instance with a name like this:

class Person {

let name: String init(name: String) {

self.name = name

}

}

var var1 = Person(name: "John")

It would look something like this in memory:

If you were to create a new variable var2 and assign it to the value of var1:

var var2 = var1

Then the references inside both var1 and var2 would reference the same place in memory:

Conversely, a structure as a value type stores the actual value, providing direct access to it. Using a struct, a similar object could be written as such:

struct Person { let name: String

}

var1 = Person(name: "John")

In memory, the variable would not point to a place in memory but the value would instead belong to var1 exclusively:

With value types, if you were to then assign this value to a new variable var2:

var var2 = var1

Then the value of var1 would be copied to var2:

Value types and reference types each have their own distinct advantages — and disadvantages. Later in the chapter, you’ll consider the question of which type to use in a given situation. For now, let’s examine how classes and structs work under the hood.

results matching ""

    No results matching ""