Classes & Structs in Swift

Reviewing important basics in Swift: distinguishing between Classes and Structs.

Commonalities of Class and Struct

  • They can define properties to store values, and they can define functions.
  • They can define initializers to set their initial state. init()
  • They can be extended, with extension
  • They can conform to protocols.

Class has these additional features:

  • Class can inherit from a parent class.
  • Classes can be deinitialized, i.e. you can call a function before the class is destroyed.?
  • Classes are reference types, while Structs are value types.

Reference types and value types

Value type:

When a value type is copied (ie, if it gets assigned, initialized, or passed into a function), each instance holds a unique copy of the data. Meaning, even if one instance of the data is changed, it does not affect any other existing instance.

Reference type:

When a reference type is copied, each instance shares the data. Meaning, if one instance of the data is changed, the change will be inflicted on all other instances.

Value or Reference - Examples:

Imagine you are a shop clerk, and you must report to your boss what you sell every day….

Value Type senario:

You write the products you sold on a piece of paper. Around closing hour, you send a copy of the paper to your boss. However, just as you send it a customer comes in and buys a product. Although you make a new sales entry, your boss will still have the old data.

Reference Type senario:

The business has a centralized cloud-based database, and you use a software to make sales records. Your boss uses the same software, and keeps track of the changes you record. Therefore if you change the data, it changes for your boss as well.

If you copy a class, you’ll have two references to one instance of the data. If you copy a struct, you’ll have two instances, each with unique copies of the data.

When to use which?

Generally, structs should be used over classes by default, unless you need the additional capabilties (mentioned earlier) the class provides.

Reading:

https://learnappmaking.com/struct-vs-class-swift-how-to/#:~:text=In%20Swift%2C%20structs%20are%20value,choice%20between%20classes%20or%20structs.

Written on October 12, 2020