[Swift] Struct vs Class

Ryan
1 min readFeb 28, 2022

Every interview I go… I see this question…

What is Struct and Class

  • They are essential building blocks of program’s code
  • In Swift, no need to create separate interface and implementation files for them

Common features of Struct and Class

  • Container that can store multiple variables
  • Using properties and methods to have structured data
  • Initializers to set up initial state
  • Can be extended to expand functionality
  • Conform to protocols to provide standard functionality
  • Access to property using subscript

Difference between Struct vs Class

Struct

  • Value type
  • Allocated in stack memory
  • No inheritance
  • Using Codable protocol, JSON ← → Struct conversion is easy
  • Always copied to new variable, every thread gets its own copy, therefore in multi-thread environment, lesser problem

Class

  • Reference type
  • Allocated in heap memory (require reference counting to dealloc)
  • Inheritance
  • Type Casting in runtime
  • deinitializer

Which to use?

  • Struct if no need for inheritance and model size is not too big
  • 1:1 mapping to JSON, Struct
  • Transfer model or save to file with serialization, Class
  • Model is also used in Obj-C, Class

Reference

--

--

Ryan

iOS engineer & data science enthusiast. Into algorithmic trading. https://github.com/Rsych