Structs vs Classes in Swift

A comparison between these fundamental programming constructs in Swift

Photo by Tamara Gak on Unsplash

The Main Difference

Let’s start with the most important thing that separate classes and structure in Swift:

Classes are reference types and structs are value types

Ok, but what exactly are reference types and value types?
And what are their differences?

Value type

struct Developer {
var name = ""
let dev = Developer() = "Paul"
let devTwo = devprint( // Paul
print( // Paul = "Rick"print( // Paul
print( // Rick

Reference type

class Developer {
var name = ""
let dev = Developer() = "Paul"
let devTwo = devprint( // Paul
print( // Paul = "Rick"print( // Rick
print( // Rick

Common Things

After discussing the main difference between the two, let’s see what they have in common.

  • Define subscripts to provide easy access to values of collections, lists, or sequences by writing one or more values in square brackets after the instance name.
  • Define custom initializers, using the init() operator, to set up their initial state.
  • Can be extended via the extension directive.
  • Can conform to protocols.
  • Can work with generics to provide flexible or reusable types.

Classes Particularities

Other than the capabilities listed above, classes have some additional properties, which distinguish them from structs:

  • Type casting, which enables you to check the type of a class at runtime.
  • Deinitializers. With the deinit() keyword, you can free up all the resources associated with an instance of a class before it is destroyed.
  • Automatic Reference Counting (ARC), that automatically manages the memory allocated to a class instance via a reference count property.
    If the reference count of a class is equal to 0, its instance is removed and the memory freed up.
  • Identity Operator. Given the fact that classes are a reference type, you can use the operators identical to === or not identical to !== to check if two variables refer to the same class instance.

What construct should you use in your code?

You should use structs, instead of classes, as your default choice and most of the time.

  • When you want to interoperate with Objective-C code.
  • When you need to control the identity of your instances.


Classes and structs in Swift look very similar but have some very important differences.

Software engineer from Italy. Just a regular guy who loves to code and learn 💻📚