Difference between a struct and a class in Swift.

Every swift developer who has at least 6 months experience will know about Struct, Enum, and Class. Everyone use them on a regular basis without knowing what they are and when and where to use them. I will try to make it simple.

Abhimuralidharan
5 min readMar 8, 2019

--

image source: stocksnap

Value Types and Reference Types

Reference: TreeHouse, Apple doc.

It is important to know the difference between value and reference types when talking about Enums, Structs, and Classes. Whenever you create an enum or a struct , it is a value type and a Class is a reference type.

  • Value Type: Struct , Enum
  • Reference Type: Class

When you pass a class object around your program, you are actually passing a reference to that object, so different parts of your program can share and modify your object. When you pass a structure [ or enum] around your program, what gets passes around is a copy of the structure. So modifications to structures don’t get shared.

One of the major benefits of value types is that they are thread-safe not requiring any synchronization.

Please read my article on Value Type vs Reference Type to understand more about value types and reference types.

Read my article on Enums in swift to understand more about enums.

An instance of a class is traditionally known as an object. But it is better to use the term Instance as we are dealing with struct and enum as well.

Class

In OOP, a class is a blueprint from which individual instances are created.

A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).

We define a class using the class keyword.

Struct

A struct is similar to a class in terms of definition and instance creation.

We define a struct using the struct keyword.

What are the common factors between struct and class?

  • Define properties to store values
  • Define methods to provide functionality
  • Define subscripts to provide access to their values using subscript syntax
  • Define initializers to set up their initial state
  • Be extended to expand their functionality beyond a default implementation
  • Conform to protocols to provide standard functionality of a certain kind

Classes have additional capabilities that structures don’t have:

  • Inheritance enables one class to inherit the characteristics of another. Struct or enum cannot do inheritance. But they can confirm to protocols.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • Deinitializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.

Since a class is a reference type and it supports inheritance, the complexity increases. In most cases, a struct should be enough to meet your needs. Use a class when they’re appropriate or necessary.

Syntax

We define a class using the class keyword and structure using a struct keyword. The syntax is the same for both struct and class.

Memberwise Initializers for Structure Types

All structures have an automatically generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name:

struct Resolution {var width = 0var height = 0}let vga = Resolution(width: 640, height: 480)

Unlike structures, class instances don’t receive a default memberwise initializer.

Note: If a struct variable is private, memberwise initializer will become private. we need to provide a public memberwise initializer in that case.

When and where to use them?

In Objective — C, everything subclasses from NSObject. NSString, NSArray etc are all reference types. On the other hand, swift is rich in value types. String, Array , Dictionary etc are all structs in swift, which is a value type. There are so many advantages in using a value type over a reference type.

Please read my article on Value Type vs Reference Type to understand more about value types and reference types.

In my opinion, we should be using struct because they greatly reduce complexity and fallback to Classes if the Struct becomes very large or requires inheritance.

  • Structs are much safer and bug-free, especially in a multithreaded environment. Swift value types are kept in the stack. In a process, each thread has its own stack space, so no other thread will be able to access your value type directly. Hence no race conditions, locks, deadlocks or any related thread synchronization complexity.
  • Use classes if you want reference types. Use structs if you want value types.
  • Even though struct and enum don’t support inheritance, they are great for protocol-oriented programming. A subclass inherits all the required and unwanted functionalities from the superclass and is a bad programming practice. Better to use a struct with protocol-oriented programming concept which fixes the above-said issue.
  • Class does support Inheritance. Class is a reference type and is stored in the heap part of memory which makes a class comparatively slower than a struct in terms of performance. Unlike a class, a struct is created on the stack. So, it is faster to instantiate (and destroy) a struct than a class. Unless struct is a class member in which case it is allocated in heap, along with everything else.
  • Value types do not need dynamic memory allocation or reference counting, both of which are expensive operations. At the same time methods on value types are dispatched statically. These create a huge advantage in favor of value types in terms of performance.

Must read: Choosing Between Structures and Classes — Apple doc

Enjoy!!

If you enjoyed reading this post, please share and give some claps so others can find it 👏👏👏👏👏 !!!!

You can follow me on Medium for fresh articles. Also, connect with me on LinkedIn.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!

--

--