Creating a data model and using the ObservableObject protocol
Let’s create a new file – although this time, choose the Swift template file rather than the SwiftUI View template – and call it DataModel
. In this file, we will put the data that we can access from ContentView
later, using the @ObservableObject
protocol.
To use this protocol, we first need to import the SwiftUI framework:
import SwiftUI
Next, we need a class to hold all the data, and we also need to make the class conform to the @ObservableObject
protocol, so let’s add that now. You can name the class anything you want, but many developers like to name the class the same name as the file it is in, so we will do the same, naming the class DataModel
:
class DataModel: ObservableObject { ...