在Swift中,CLPlacemark崩溃

3
我正在使用CLGeocoder进行逆地理编码并获取CLPlacemark数组。当我在美国以外的地方使用GPS(例如-27,127),然后访问placemark.postalCode时,应用程序会崩溃并显示以下信息:

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

看起来,当没有邮政编码可用时,placemark.postalCodenil。但是在Swift中,postalCode的返回类型是String!var postalCode: String! { get } // zip code, eg 95014 因此,我甚至无法测试它是否为nil,因为崩溃是由postalCode的getter引起的。
有什么想法可以防止这种崩溃吗?谢谢!
1个回答

6
作为一个可选项,即使它被隐式解包了,你也可以检查它是否为nil:
if placemark.postalCode != nil {

}

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

为了证明这一点,在playground中尝试运行以下代码,其中对2个隐式解包属性(计算属性和存储属性)进行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")
}

当然,你是对的。我没有意识到这一点。谢谢! - VojtaStavik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接