CLPlacemark在Swift中崩溃

Voj*_*vik 2 xcode ios clgeocoder swift clplacemark

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

"致命错误:在打开一个Optional值时意外地发现了nil".

看来,这placemark.postalCodenil没有邮政编码的地方.但是postalCodeSwift中的返回类型是String!:

var postalCode: String! { get } // zip code, eg. 95014

所以我甚至无法测试nil,因为崩溃是由吸气剂引起的postalCode.

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

Ant*_*nio 5

作为一个可选项,即使是隐式解包,您也可以将其检查为nil:

if placemark.postalCode != nil {

}
Run Code Online (Sandbox Code Playgroud)

并且应用程序不会因为那个崩溃:)

为了证明这一点,只需在操场上尝试此代码,其中检查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")
}
Run Code Online (Sandbox Code Playgroud)