Understanding Swift Value Semantics

Jimmy M Andersson
5 min readNov 26, 2018

Even if you’re just getting started with programming, chances are big that you’ve stumbled across Value Types. You may not even realize you’re working with them, but they come with some very interesting and good-to-know attributes that we will look into in this article.

Conceptual sketch of a stack storing two Value Types.

What Are Value Types?

You may know that a class is a Reference Type and that you are able to share the reference to an object between different variables. You may also know that this feature enables you to change the state of said object through not just one, but infinitely many variables like so:

class MyReferenceType {
var a: Int
init(a: Int) {
self.a = a
}
}
var R1 = MyReferenceType(a: 1)
var R2 = R1
R2.a = 42
print(R1.a, R2.a)
// Prints "42 42"

The fact that many different variables are able to mutate the same object is sometimes referred to as an alias problem, and it can produce some seriously hard-to-track-down bugs if you’re not careful.

A Value Type, on the other hand, behaves more like we’d expect the standard primitive types to behave. This means that all the things you would expect an int, double, or float to do, a Value Type will do too. For example, if you perform the operations below, you would expect the variable b to have its…

--

--

Jimmy M Andersson
Jimmy M Andersson

Written by Jimmy M Andersson

Software engineer with a passion for data and machine learning

Responses (1)