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

Hello I am developing a map application in which I feed in the latitude and longitude, but I am new to MapKit, and so I tried the following code …

Import SwiftUI
import MapKit

struct ContentView: View
{
    var lat: Double = -37.8136
    var lng: Double = 144.9631
    
    
    @State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: lat, longitude: lng), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
    var body: some View
    {
        
        Map(coordinateRegion: $region)
         .frame(width: 400, height: 300)
    }
}

But I get. the following error message…
Cannot use instance member 'lat' within property initializer; property initializers run before 'self' is available
Cannot use instance member 'lng' within property initializer; property initializers run before 'self' is available

Hpw can do this so that I can produce a map for any give ‘lat’ and ‘lng’?

Thank you sincerely.

Try this Michael.

import SwiftUI
import MapKit

struct ContentView: View {
    @State var lat: Double = -37.8136
    @State var lng: Double = 144.9631
    @State var region: MKCoordinateRegion = MKCoordinateRegion()

    var body: some View {
        VStack {
            Map(coordinateRegion: $region)
                .frame(width: 400, height: 300)
        }
        .onAppear {
            region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: lat, longitude: lng), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
        }
    }
}

You can’t create a property in a struct that uses another property of that struct that is also being initialised as the same time since they are both being initialised as the struct is created. That’s what the error is alluding to.

Declaring region as a @State property enables it to be mutable (can be changed). Struct variables are immutable by default and @State is a special property wrapper that allows them to be changed. In the code above, region is initialised as an MKCoordinateRegion() and by using the view modifier .onAppear we can perform some work setting up the region details as the View is created.

I hope this sort of makes sense.

Thank you sincerely, although I did manage to figure it out.