gpt4 book ai didi

swift - 我怎样才能得到用户邮政编码

转载 作者:行者123 更新时间:2023-11-28 15:47:24 24 4
gpt4 key购买 nike

我正在使用 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!”,应用程序会崩溃并创建 nil。该应用程序不会崩溃,但我无法获取邮政编码。它在 swift 2 上工作。有什么帮助解决这个问题吗?

最佳答案

正如@ashley-mills 所指出的,它们是两种不同类型的信息。当您期望 nil 是可能的,或者即使您不期望它时,最好的解决方案是使用以下类似的方法保护您自己免受现金侵害。

guard let getlocation = placemarks.postalCode else { print("Returned Nil"); return }
print(getlocation) // notice no unwrap need

关于swift - 我怎样才能得到用户邮政编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42811574/

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