CLPlacemark crash in Swift

*爱你&永不变心* 提交于 2019-12-11 03:22:19

问题


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:

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

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

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

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!


回答1:


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 :)

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")
}


来源:https://stackoverflow.com/questions/27671435/clplacemark-crash-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!