0

Im trying to pass data into a swiftui view to be displayed when it is initialized, but am having trouble getting it to work.

Here is my code which passes data into my 'MarkerInfoWindow.swift' view:

func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {
    print("Showing marker infowindow")
    print("marker.userData: \(marker.userData)")
    let mUserData = marker.userData as? [String:String]
    print("mUserData?['name']", (mUserData?["name"]) ?? "mUserData[name] was nil")

    let mInfoWindow = UIHostingController(rootView: MarkerInfoWindow(placedata: mUserData!))

    return mInfoWindow.view
}

Here is the code to my 'MarkerInfoWindow.swift' view:

struct PlaceDataStruct {
    var name : String
    var place_id : String
}


struct MarkerInfoWindow: View {

    var placedata: [PlaceDataStruct]  

    var body: some View {

        //Here is where i keep getting errors regardless if i use this method or dot notation
        Text(placedata["name"])

    }
}

Im not sure if im implementing my PlaceDataStruct incorrectly. Does anyone know what I'm doing wrong, so that I can display the right data every time my view is initialized?

4

1 回答 1

1

You’re MarkerInfoWindow is expecting an array of structs but the data you are passing is a dictionary, in the form [String: String]

You should update your MarkerInfoWindow to accept a dictionary instead. Here is an example of how to do that.

struct MarkerInfoWindow: View {

    var placedata: [String: String]  // update to be dictionary

    var body: some View {

        Text(placedata["name", default: ""]) // use correct notation for accessing dictionary

     }
 }

You’re also force unwrapping the data before you pass it to your MarkerInfoWindow if that’s your intention that is ok. But note that if your data isn’t there then it will crash your app.

于 2019-11-13T16:34:28.217 回答