Sometimes you might be unable to create an observed object using the @ObservedObject
annotation, for example if you need to use the object in the init()
function of a view. When this happens there is a different way of creating an observed object, which is by using the ObserverObject
initializer:
var ProjectView: View {
@ObservedObject let project: Project
init(project: Project) {
_project = ObservedObject(initialValue: project)
}
var body: some View {
// ...
}
}
Note the underscore in front of _project
, this is basically telling Swift to replace the underlying variable created by the @ObservedObject
annotation.
You can also apply the same principle to other annotations such as @State
or @FetchRequest
.