我正在使用swift 3.我对此代码有问题,以获得这样的邮政编码" US"并将其保存到var。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if error != nil {
print("Location Error!")
return
}
if let pm = placemarks?.first {
self.showlocation(pm)
} else {
print("error with data")
}
})
}
func showlocation(_ placemarks: CLPlacemark) {
self.locationm.stopUpdatingLocation()
print("Location done")
// getlocation = placemarks.postalCode! "this string var is nil"
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location Error: " + error.localizedDescription)
}
代码中没有错误,但是应用程序崩溃,如果我刚刚删除" getlocation = placemarks.postalCode!"应用程序不会崩溃,但我无法获得邮政编码。它正在研究swift 2.有任何帮助解决这个问题吗?
答案 0 :(得分:1)
正如@ ashley-mills指出的那样,它们是两种不同类型的信息。当你期望零可能成为可能时,或者即使你不期望它,最好的解决方案是保护你的自己免受现金的影响,如下所示。
guard let getlocation = placemarks.postalCode else { print("Returned Nil"); return }
print(getlocation) // notice no unwrap need
答案 1 :(得分:0)
getlocation = placemarks.postalCode!
为:
getlocation = placemarks.isoCountryCode!
我不知道邮政编码在swift 3中不起作用的区别是什么?