VojtaStavik
VojtaStavik

Reputation: 2482

CLPlacemark crash in Swift

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!

Upvotes: 3

Views: 1133

Answers (1)

Antonio
Antonio

Reputation: 72790

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

Upvotes: 6

Related Questions