Value and Reference Types

May 22, 2020

JP McGlone

In Swift, there are two fundamental categories of Types: “value types” and “reference types”.

The difference is simple. When we copy (assign, initialize or pass as an argument) a value type, we create an independent instance with its own copy of the data. However, when we copy (again, that’s assign, initialize or pass as an argument) a reference type we create a shared instance.

In the spirit of brevity, let’s look at two quick examples:

// Value Type
struct Person {
    var name: String
}

var steve = Person(name: "Steve Wozniak")
var otherSteve = steve

steve.name = "Steve Jobs"

print(steve.name) // Steve Jobs
print(otherSteve.name) // Steve Wozniak

Although I assigned the variable otherSteve to the variable steve, steve and otherSteve are not referencing the same data. I copied the data from one to the other, which allows us to make changes to steve without affecting otherSteve (and the other way around! Try it!).

Now let’s look at a “reference type” example:

// Reference Type
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var steve = Person(name: "Steve Wozniak")
var otherSteve = steve

steve.name = "Steve Jobs"

print(steve.name) // Steve Jobs
print(otherSteve.name) // Steve Jobs

What you’ll notice here is that changing steve.name to “Steve Jobs” also changed otherSteve.name to “Steve Jobs”. Why did this happen?

A class is a reference type. In the second example, I made Person a class (not a struct like in the previous example). When we assign an instance of a class to a variable, like this:

var steve = Person(name: "Steve Wozniak")

— a reference to a single instance is stored in the variable. Let’s imagine that reference’s address is “4815162342”.

In the later line, when I write var otherSteve = steve, I am not creating a new instance of the data. Instead, I am assigning the reference (that is, address “4815162342”) to otherSteve.

In other words, steve and otherSteve are both referencing the exact same instance of Person — setting the name on one is setting the name on the other.

I hope this clears up the difference between “value” and “reference” types!

If you have any questions, please hit us up at @SwiftGuild on Twitter!


JP McGlone

iOS Engineer

© 2021   

Swift Guild by JP McGlone, LLC