I have the following unwrapping line in my code:
UIApplication.sharedApplication().openURL((NSURL(string: url)!))
Sometimes there occurs this fatal error:
fatal error: unexpectedly found nil while unwrapping an Optional value
I know why this error sometimes occurs, but is there a way to make a try - catch statement around this line?
No, this is not what try and catch are for. !
means "if this is nil, then crash." If you don't mean that, then don't use !
(hint: you very seldom want to use !
). Use if-let
or guard-let
:
if let url = NSURL(string: urlString) {
UIApplication.sharedApplication().openURL(url)
}
If you already have a try
block and want to turn this situation into a throw
, that's what guard-let
is ideal for:
guard let url = NSURL(string: urlString) else { throw ...your-error... }
// For the rest of this scope, you can use url normally
UIApplication.sharedApplication().openURL(url)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With