Learning Swift

Prefer Struct over Class in Swift

Explain why is Struct the first choice instead of Class for Swift

Nov 15, 2020 · 5 min read
Image for post
Image for post
Photo by Dan Gold on Unsplash

In Swift, we have Class and Struct. They are similar with some distinct differences as stated in the doc.

Image for post
Image for post

All the goodies of Class, which made one think let’s use class. But it does state

Is using Struct just because it’s more efficient, but losing out some great features? In Choosing Between Structures and Classes, it does provide some guidance when to choose what, by why is Struct better? My views below…

No inheritance for Struct

In Swift, one of the differences between Class and Swift

  • A class can inherit from another class.
  • A struct cannot inherit from anything. It can conform (implements) a protocol though.
Image for post
Image for post
protocol Aprotocol { }class ParentClass: Aprotocol { }
class ChildClass: ParentClass { }
struct ParentStruct: Aprotocol { }
struct ChildStruct: ParentStruct { } // Error

The above, the error is Inheritance from non-protocol type ‘ParentStruct’. The error message is a little misleading, as there’s no inhertance from protocol too. It’s conforming or implementing the protocol. Technically there’s no inheritance for Struct.

Why is no inheritance better?

Object-oriented is only suitable for cases where the base is relatively stable and not changing as much. Deeply nested inheritance making software architecture less agile.

In fact what most developers needs are just a protocol to conform to, instead of a base object to inherit from. The ability to inherits might make on using it wrongly, and complicate the architecture. Hence having struct not-inheritable reduce that error.

You can get more insight into why languages evolve in the below article.

Value Type for Struct

In Swift, another of the differences between Class and Swift is

  • A class is Reference Type. Two classes could point to the same thing.
  • A struct is Value Type. Each struct is unique and independent of each other.
Image for post
Image for post
class Aclass { var value = 0 }
struct Astruct { var value = 0 }
let classA = Aclass()
var classB = classA
classB.value = 1
print("\(classA.value) \(classB.value)") // result is 1 1
let structA = Astruct()
var structB = structA
structB.value = 1
print("\(structA.value) \(structB.value)") // result is 0 1

For classes, the copy is by reference. It is more efficient when copying, but they are referring to the same object. Change in one will affect the other. This allows the value of an immutable object to still mutate.

  • i.e. altering classB.value will change classA.value, even classA suppose to be immutable (i.e. using let)

For struct, each copy is unique to itself. A copy operation will truly copy the entire struct as a new copy. Changing the copy of the struct will never alter the original struct.

Why is by value better?

Having struct store by value is safer, especially if we are using it as data storing. There’s no chance someone else can alter the content of it indirectly.

While By Reference could be useful in some cases, most of the time, what we really need is an object that is self-sustaining, independent, and truly immutable when it is let. (describe next)

Struct is Truly Immutable

We know in Swift, let is immutable and var is mutable.

But if we apply to a Class as below, we notice even if it is let, we can still change the internal value.

class A { var value = 10 }
let a = A()
a.value = 20 // Okay, can still mutate it even a is let

However, for struct, it is an error.

struct A { var value = 10 }
let a = A()
a.value = 20 // Can't assign to property: 'a' is a 'let' constant

It’s because classes are reference types, only the memory location is immutable, but the content mutability is independent from it.

Hence that makes Struct immutability more guaranteed than Class.

Besides the above, there are more defensive mechanism handled explicitly in Struct to certain its mutability such as

  • Avoiding internal function from mutating internal variable
  • Needing self capturing during construction of closure

They are all explained in more detail in the article below.

Why is true immutability better?

Immutability will provide better assurance of the data consistency. One can be fully assured that the value internally is not accidentally altered by any external means. This helps especially in any multi-threaded environment.

Hence in such case, Struct again provides a better form for Class.

Simple Constructor and No Deinit

Struct is meant to be an easier version of Class. It is a much better structure to be store pure data and properties. Hence Swift decided to simplify one initialize the Struct and remove deinit from it.

Automatic memberwise initializer creation

For a simple pure data and property struct, it’s a hassle to create an init constructor for them.

To simplify the use of Struct, Swift will automatically generate the init constructor for it. It is called memberwise initializer, as per the documentation.

struct Size { 
var width = 0.0, height = 0.0
let twoByTwo = Size(width: 2.0, height: 2.0)

So simple!

No deinit function

A class has a lifecycle of construction and destruction. In Swift, this is called deinit. As Swift Automatic Reference Counting, one doesn’t need to manually deallocate memories as one does back in the days of C.

Nevertheless, for some more complex structures, this deinit is available for one to do any cleanup. This is only available in Class and not Struct. The reason is, for Struct, one is not expected to have such a complex structure in place.

Above is my view and learning of why Struct is preferred over Class as the initial option. Only when Struct is not meeting one’s need, Class is there to aid.

Mobile App Development Publication

Sharing Mobile App Development and Learning


Written by


Passionate about learning, and sharing mobile development and others https://twitter.com/elye_project https://www.facebook.com/elye.proj

Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning


Written by


Passionate about learning, and sharing mobile development and others https://twitter.com/elye_project https://www.facebook.com/elye.proj

Mobile App Development Publication

Sharing iOS, Android and relevant Mobile App Development Technology and Learning

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store