Implementing a CoreLocation wrapper as @ObservedObject
We mentioned in the introduction to this chapter that @State
is used when the state variable has value-type semantics. This is because any mutation of the property creates a new copy of the variable, which triggers a rendering of the view's body, but what about a property with reference semantics?
In this case, any mutation of the variable is applied to the variable itself and SwiftUI cannot detect the variation by itself.
In this case, we must use a different property wrapper, @ObservedObject
, and the observed object must conform to ObservableObject
. Furthermore, the properties of this object that will be observed in the view must be decorated with @Published
. In this way, when the properties mutate, the view is notified, and the body is rendered again.
This will also help if we want to bridge iOS foundation objects to the new SwiftUI model, such as CoreLocation functionalities. CoreLocation is the iOS framework...