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()
dev.name = "Paul"
let devTwo = devprint(dev.name) // Paul
print(devTwo.name) // Paul
devTwo.name = "Rick"print(dev.name) // Paul
print(devTwo.name) // Rick

Reference type

class Developer {
var name = ""
}
let dev = Developer()
dev.name = "Paul"
let devTwo = devprint(dev.name) // Paul
print(devTwo.name) // Paul
devTwo.name = "Rick"print(dev.name) // Rick
print(devTwo.name) // 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.

Conclusions

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 💻📚