'Property initializers run before 'self' is available Error?

I am trying to make the map in my app update its style URL based on the device being in dark-mode or light-mode. However I am getting the error below where I declare let mapView: MGLMapView.

"Cannot use instance member 'mapboxStyleURL' within property initializer; property initializers run before 'self' is available"

Why is this not working?

Thank you!

struct MapboxMapViewRepresentable: UIViewRepresentable {
    @Environment(\.colorScheme) var colorScheme
  
    var mapboxStyleURL: String {
            "mapbox://styles/mpstddb/" + (colorScheme == .dark ? "cl0318cec000k14qtognrshos" : "ckwih3qvma5n916oiz7403d0h") + "ModeUrl"
    }
            
    func makeCoordinator() -> Coordinator {
        return Coordinator(control: self)
    }
    
// Cannot use instance member 'mapboxStyleURL' within property 
// initializer; property initializers run before 'self' is available
    let mapView: MGLMapView = MGLMapView(frame: .zero, styleURL: URL(string:  mapboxStyleURL)!)
        
    func makeUIView(context: Context) -> MGLMapView {
        mapView.showsUserLocation = true
        mapView.delegate = context.coordinator
        return  mapView
    }
   
    func setCenterAt(coordinate : CLLocationCoordinate2D) {
        mapView.setCenter(coordinate, zoomLevel: MapViewModel.startAtZoomLevel, animated: false)
    }
    
    func updateUIView(_ mapView: MGLMapView, context: Context) {
       
    }
    
}



Solution 1:[1]

The error clearly says that you cannot use self while initializing a property on the top level of a struct or class.

Initialize it lazy. The initial value is assigned (once) when being accessed the first time.

lazy var mapView: MGLMapView = {
    return MGLMapView(frame: .zero, styleURL: URL(string:  mapboxStyleURL)!)
}()\

Edit:

In a struct conforming to UIViewRepresentable creating the map view lazily is wrong. You have to create it in makeUIView

func makeUIView(context: Context) -> MGLMapView {
    let mapView = MGLMapView(frame: .zero, styleURL: URL(string:  mapboxStyleURL)!)
    mapView.showsUserLocation = true
    mapView.delegate = context.coordinator
    return  mapView
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1