Using Structs and Classes for Effective Management and Testing in Swift

Make it a struct, please

Steven Curtis
4 min readAug 8, 2024
Photo by Centre for Ageing Better on Unsplash

As iOS developers we need to think about the best way to use data structures.

I want to explore a specific scenario where it makes sense to use a struct in an app, and matching classes in the test code.

Terminology

class: A reference type, uses reference semantics and is allocated on the heap

struct: A value type, uses value semantics and is allocated on the stack

Comparing classes and structs

Structs are more performant than classes as they do not require heap allocation and deallocation (They are stored on the stack). For this reason alone it makes sense to default to structs if we have the choice between a class and a struct in our implementation.

However, there are further differences.

Structs are copied by value, whereas classes are copied by reference. Value semantics are clear and simple, and make structs easy to understand for developers. However classes support inheritance and reference semantics which may be required for certain use cases.

An Example

--

--