We use classes and structures to craft our code. They are similar in many ways, and I'll list a few, but this post is mainly about how they differ and how I choose which one to use based on these differences.
There are many similarities between Structs and Classes. They both:
- Can contain stored properties
- Define initializers to set up their initial states
- Use subscript syntax to to access properties or functions
- Implement methods
- Utilize extensions - and more!
While it’s good to know the similarities, the differences determine how I choose whether to use a Class or Struct. Here are some noteworthy differences:
The biggest differentiation is that Structs are value types and classes are reference types. Value types are copied when passed around in your code, while reference types are passed by references. Attached below is a Playground file with further explanations and an example (for the difference between value and reference types, as well as mutating functions).
Classes have inheritance, structs do not.
Classes are mutable, while structs are immutable (which is why we are prompted by Xcode to use ‘mutating’ when creating a function that changes values in a structure)
Classes (reference types) are stored in the heap, while Structs (value types) are added to a stack (this is something I’m still gaining a better understanding of, but I know that due to the way that stacks function structures are processed more quickly than classes).
How do I choose which to use? Right now, I keep my decisions simple. If I’m dealing with a relatively small amount of data I use a struct. For bigger tasks (like networking) I use a class. How do you choose between a Structure or Class?
The example playground can be found here!