Search code examples
swiftxcode6google-maps-sdk-ios

Working with userData as a Dictionary


I need my markers to hold a few pieces of data (more than just location, snippet, and title, they are already in use). I have created a dictionary and then set marker.userData as this dictionary. However, I am having problems getting the values back out of this dictionary. Any help would be appreciated.

var mapDict : [String : Bool] = [ "Accredited" : self.accredited,
                             "Accepts Infants" : self.acceptsInfants,           
                           "Accepts Preschool" : self.acceptsPreschool,
                           "Accepts Schoolbag" : self.acceptsSchoolage, 
                               self.slug.last! : false]
marker.userData  = mapDict

When I then use

func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool {
    println(marker.userData)
}

I get (which is the correct data)

{
    "Accepts Infants" = 0;
    "Accepts Preschool" = 1;
    "Accepts Schoolage" = 0;
    Accredited = 0;
    "little-steps" = 0;
}

However, I can't figure out how to access each of those values individually to display them to the user. The problem seems to be that userData is an AnyObject and not a Dictionary (and cannot be downcast as a dictionary, string etc).


Solution

  • You can do a conditional to get a dictionary out of this,

    if let dict = userData as? [string:Int] {
        //dict is now a Dictionary
    } else {
        // something went wrong with the cast 
    }
    

    I'm on mobile, sorry for the format.