Class vs Struct in Swift

Priyanka Saroha
Swiftable
Published in
3 min readSep 9, 2023

In Swift class and struct are very much similar both of which can have:

  • Properties to store values.
  • Methods to provide functionality.
  • Subscripts to provide access to their values using subscript.
  • Initializers to set up their initial state.
  • Extension to expand their functionality.
  • Protocol conformation.

There are some extra capabilities which class provides:

  • Inheritance from one class to another.
  • Type casting to check and interpret the type of a class instance at runtime.
  • Deinitializers to free assigned resources.
  • Allows to have more than one reference to a class.

One major difference is that a struct is a value type whereas a class is a reference type:

Struct is a value type:

As struct is a value type so whenever a copy of its instance is created then it will be treated as a complete new copy which has its own copy of properties.

In below example, when there is a change in name of a Student instance's copy, it will not be reflected in the original instance's name.

Class is a reference type:

As class is a reference type so whenever a copy of its instance is created then it will have reference to the original instance. So whenever any change will be there in original instance or copy of instance, it will reflect in both instances.

In below example, when there is a change in name of a Student instance's copy, it will be reflected in the original instance's name as well.

A struct and a class behavior with contant(Mutability):

There is concept of mutability of instance in case of struct and class, when they are declared as constant with letkeyword.

In below example, a new copy of class instance is created as constant but still it allows to modify the name of student.

When a class instance is declared using let then all of its properties can be modified. But its not the case with a struct, a constant struct does not allow to mutate its properties even when they are declared as var.

In below example, a new copy of struct instance is declared as let to make it constant. But unlike a class, it does not allow to modify a constant struct properties.

Join the Swiftable Community to connect with iOS Engineers.

--

--

Priyanka Saroha
Swiftable

iOS developer with almost 9 years of rich experience which includes a good knowledge of ObjectiveC, Swift, SwiftUI and AR.