得到“意外发现无零,同时解开一个可选值”错误

问题描述:

我使用谷歌地图API放置和使用坐标放在苹果地图上的注释。得到“意外发现无零,同时解开一个可选值”错误

我现在想要做的是将坐标转换为名称和地址,并将其用于Ekreminder。这是到目前为止我的代码,但我得到的错误“致命错误:意外发现零而展开的可选值”当我尝试运行它:

addLocationReminderViewController.name = self.mapItemData.placemark.name 

    // Construct the address 
    let dic = self.mapItemData.placemark.addressDictionary as Dictionary! 
    let city = dic["City"] as! String 
    let state = dic["State"] as! String 
    let country = dic["Country"] as! String 
    addLocationReminderViewController.address = "\(city), \(state), \(country)" 
} 

编辑这是怎么即时得到的信息:

    if data != nil{ 
        let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! NSDictionary 

        let lat = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as! Double 
        let lon = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as! Double 
        let point = MKPointAnnotation() 
        point.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) 
        point.title = self.resultsArray[indexPath.row] 
        let region = MKCoordinateRegion(center: point.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)) 
        dispatch_async(dispatch_get_main_queue(), {() -> Void in 
         self.mapView.setRegion(region, animated: true) 
         self.mapView.addAnnotation(point) 
         self.mapView.selectAnnotation(point, animated: true) 
         // 
         let placemark = MKPlacemark(coordinate: point.coordinate, addressDictionary: nil) 
         let mapItem = MKMapItem(placemark: placemark) 
         self.mapItemData = mapItem 
         // 
        }) 
+0

你真的认为'Dictionary!'? – GoZoner

您正在用“as!”将“City”,“State”和“Country”的字典参考依据铸造成String。如果它们中的任何一个不存在于字典中,或者不是字符串,那么你会得到你的致命错误。

您打算如何处理格式错误的字典?你可以使用

if let city = dic["City"] as? String, 
    let state = dic["State"] as? String, 
    let country = dic["Country"] as? String { 
    // you now have your values 
    addLocationReminderViewController.address = "\(city), \(state), \(country)" 
} 
else { 
// something is wrong 
} 
+0

已更新...感谢您的回复 – Tim