Value and Reference Types

Enums, Structs, and Classes

What are value types (enums, structs) good for?

Enums and structs are not the only value types in Swift. Arrays, strings, numbers, tuples, and dictionaries are all value types, too.

  • for storing and passing around data (bank account balance, for example)

What are reference types good for?

When multiple objects need to work with the same reference, same instance. For example, bank account holder (user) should be a class object.

If the name of the account holder changes, all the other objects that have a reference to the account should know about it.

Stored vs. computed properties

Enums, classes, and structures — all can provide computed properties.

Only classes and structures can provide stored properties. Enums can’t.

Do you have stored properties? -> Use struct or class.

Storing vs. manipulating data

Value types store data, but they usually don’t manipulate that data. Their responsibility is to store data. It is the owner of the value that manipulates the data stored by the value.

What should I use?

Use enums. When you can’t use enums, use structs. When you can’t use structs, use classes.

Objects that will conform to NSObjectProtocol have to be class objects. For example, a table view’s data source class has to inherit from NSObject and therefore can not be a struct. Structs can’t inherit from NSObject.
- Joe Fabisevich 🐶🐳🐒™