Swift: Class vs Struct
Classes and Structs are very similar to one another. They both store data and model behavior.
- They both define properties to store values. Much like a key-value pair in Hash Maps.
- They both have initializers to create instances with initial values. Objects can be created with initialized values to start with.
- They can both conform to protocols. Some protocols are specific to classes, so only classes can conform to that specific protocol, but otherwise both can conform to it.
- They can be extended via extensions for inheritance from other classes/structs.
Class Specific Capabilities
- Classes can inherit other classes characteristics.
The main difference between classes and structs is that classes are a reference type, and structs are value type objects. Let’s look at what this means in terms of code.
The last line of code is what is the most important.
cat.name prints “hound”, because the reference
cat.name both point to the same instance. So when
dog is changed,
cat is changed along with it. They both refer to the same object or instance that is created in RAM memory space, and refer to the same memory address.
In struct however,
cat.name prints “dog”, even though
dog.name has been reassigned to “hound”, because structs point to separate instances. A value type means that the value is copied at the time of assignment to a variable or constant, or when it’s passed to a function. They refer to separate instances however, which is the most important part to remember.
When to Use What
Use a class when you want to control identity, or keep the reference to the same object. This ensures that the identity of the object will not change throughout the app. Sort of like a constant when comparing variables and constants.
You can use structs almost any time. Think of them as the variable when comparing variables and constants.
Some examples of structs: strings, arrays, numbers, dictionaries
We use structs when we don’t control identity. For instance, when you fetch data form servers, there may be times where the objects are the same, but since you’re not controlling identity, it’s best to use structs.