SwiftUI: Publishing changes from within view updates is not allowed, this will cause undefined behavior

Viewed 69

I've read a number of questions about this error that relates to dismissing sheets, but none dealing with SwiftUI's Map. The following code generates this error. Nothing is being updated in the view model. I'm simply passing a binding to a region into the Map initializer. Using a local state variable for region works with no error. I'm running Xcode 14.0. If I remove the @Published property wrapper then the error goes away. So I'm confused as to how the view model should notify the view that the region has changed, perhaps due to location updates.

import SwiftUI
import MapKit

class MM : ObservableObject {
    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
}

struct SimpleMap: View {
    @ObservedObject var mm = MM()
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))

    var body: some View {
        //Error
        Map(coordinateRegion: $mm.region)
        
        //No Error
        //Map(coordinateRegion: $region)
    }
}

0 Answers
Related