Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try and catch around unwrapping line? Swift 2.0, XCode 7

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?

like image 773
Philipp Januskovecz Avatar asked Nov 22 '15 21:11

Philipp Januskovecz


1 Answers

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)
like image 164
Rob Napier Avatar answered Nov 30 '22 08:11

Rob Napier