If you aren’t careful, you can mutate constants!

Using Structs over Classes in Swift Isn’t as Safe as You Think It is

Good discipline should be more of a concern than using a value type over a reference type

Kenny Dubroff
DevGauge
Published in
5 min readSep 4, 2021

--

If all you’re doing is using structs over classes, your code isn’t necessarily safe

If you’ve been doing Swift Development for any length of time, I’m sure you’ve heard that it’s good practice to use a struct over a class by default. While this is true in many cases, and for good reason, it’s very easy for a struct to be just as unsafe as a class. Read on to learn more.

Why do people say to use structs over classes by default?

Common advice given to Swift Developers is to use a struct by default, and only use a class when you have to. Let’s explore the reasons why and see why this line of thinking isn’t necessarily correct for all situations.

Structs are value types

Structs, being value types, are easier to manage on the memory side of things since each one is a unique copy. Instances of reference types on the other hand are a reference to some point in memory.

As you can see with the following (contrived) example, if you make a copy of a value type and mutate one, the other…

--

--

Kenny Dubroff
DevGauge

I’m a Full Stack iOS Developer with a passion for writing clean, reusable code.