点击标记时打印特定键的用户数据

Print UserData for specific key when a marker is tapped

我添加了一个标记

var marker:  GMSMarker?
let position = CLLocationCoordinate2D(latitude: 38.890106, longitude: -77.007362)
marker = GMSMarker(position: position)
var data = Dictionary<String, Any>()
data["type"] = "Mark1" as String
marker?.userData = data
marker?.map = self.map

现在 func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { 我想获取 `["type"] 值,当我这样做时:

    if marker.userData["type"] == "Mark1" {
        print("It's Marker type 1")
    }

我收到错误:

Value of type 'Any' has no subscripts

我已经搜索堆栈溢出并出现上述错误,该解决方案与我的问题无关,因为它与地点无关。

更新 如果我简单地打印:print(marker.userData!) 我得到:

{
    type = Mark1;
}

但我无法读取 If 条件中的类型。

试试这个

   func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {


    guard let data = marker.userData as? [String:Any] else{return false}
    guard let type = data["type"] as? String else{return false}
    if type == "Mark1"  {
        print("It's Marker type 1")
    }
    return true
}