Instruct Your View With A ViewModel: Should It Be A Class or a Struct?
Another choice?
--
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 12.0.1, and Swift 5.3
Terminology:
struct: An object defined in Swift, using pass by value semantics
class: An object that defines properties and methods in common
Prerequisites
- Be able to create a basic Swift application
- You might also like to see the following video to help you out with the differences between Structs and Classes — https://youtu.be/xhfXJ7a2LG8
There are a couple of different ways you can create your ViewModel if you implement the MVVM architecture.
If you’d prefer a video, don’t worry — I’ve got you covered: https://youtu.be/xhfXJ7a2LG8
A comparison project
I’ve created a simple project that has one view using a class
for the view model, and one using a struct
for the view model.
We can see the two view models (see the rather rubbish function that can print to the console).
and
which is then used in turn from the view controllers:
and