gpt4 book ai didi

swift - 收到 "unexpectedly found nil while unwrapping an Optional value"错误

转载 作者:行者123 更新时间:2023-11-30 13:45:38 27 4
gpt4 key购买 nike

我使用谷歌放置 API 并使用坐标在苹果 map 上添加注释。

我现在想做的是将坐标转换为姓名和地址并将其用于 Ekreminder。到目前为止,这是我的代码,但当我尝试运行它时,出现错误“ fatal error :在解包可选值时意外发现 nil”:

    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
//
})

最佳答案

您正在使用 as! 将“City”、“State”和“Country”的字典引用“盲目”转换为 String。如果其中任何一个不存在于字典中或者不是字符串,那么您将收到 fatal error 。

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

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
}

关于swift - 收到 "unexpectedly found nil while unwrapping an Optional value"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34976953/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com