Class vs Struct in Swift

Sisitha jayawardhane
3 min readMay 24, 2022

--

When we need to decide how to store data and model behavior, there are two choices: Classes and Structs.

Let’s talk about what are their differences.

The main difference between those two is that Classes are reference type, Structs are value type objects. Okay but what does it mean?

What is a reference type?

When we are initializing an object, RAM allocates memory space and address to it. Then, assigns its memory address to the object we created.

Let’s see this with an example.

We have an Animal class that only has a name property. Then, we create a dog object and create cat object but assign dog to the cat object.

Since they are reference type objects, they are pointing to the same memory address, so they are actually the same objects! If we change one of their property, other one will be affected as well because they are pointing to the same address. Let’s take a look below.

Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used.

What is a value type?

A value type is a type whose value is copied when it’s assigned to a variable or constant, or when it’s passed to a function.

Let’s see the above example with minor modifications.

Then we talk about Protocols

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.

--

--

Sisitha jayawardhane

Undergraduate Software engineering student at University of Kelaniya