Swift 中的 CLPlacemark 崩溃 [英] CLPlacemark crash in Swift

查看:41
本文介绍了Swift 中的 CLPlacemark 崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CLGeocoder 进行反向地理定位并获取 CLPlacemark 数组.当我在美国以外使用 GPS(即 -27,127)然后访问 placemark.postalCode 时,应用程序崩溃:

I'm using CLGeocoder for reverse geolocation and get array of CLPlacemark. When I use GPS outside the US (i.e. -27,127) and then access placemark.postalCode, the app crashes with:

致命错误:在展开可选值时意外发现 nil".

"fatal error: unexpectedly found nil while unwrapping an Optional value".

看起来,placemark.postalCodenil,其中没有可用的邮政编码.但是 postalCode 在 Swift 中的返回类型是 String!:

It seems, that placemark.postalCode is nil where no postal code is available. But postalCode return type in Swift is String!:

var postalCode:字符串!{ get }//邮政编码,例如.95014

所以我什至不能测试nil,因为崩溃是由postalCode的getter引起的.

So I can't even test is for nil, because the crash is caused by the getter of postalCode.

任何想法如何防止这种崩溃?谢谢!

Any ideas how to prevent this crash? Thank you!

推荐答案

作为一个可选的,即使隐式解包,你也可以检查它是否为零:

Being an optional, even if implicitly unwrapped, you can check it for nil:

if placemark.postalCode != nil {

}

应用程序不会因此崩溃:)

and the app won't crash because of that :)

为了证明这一点,只需在操场上试试这段代码,其中 2 个隐式展开的属性(一个计算的和一个存储的)被检查为零:

To prove it, just try this code in a playground, where 2 implicitly unwrapped properties (a computed and a stored) are checked for nil:

struct Test {
    var nilComputed: String! { return nil }
    var nilStored: String! = nil
}

var test = Test()

if test.nilComputed != nil {
    print("It's not nil")
} else {
    print("It's nil")
}

if test.nilStored != nil {
    print("It's not nil")
} else {
    print("It's nil")
}

这篇关于Swift 中的 CLPlacemark 崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆