Try and catch around unwrapping line? Swift 2.0, X

2019-02-20 22:53发布

问题:

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?

回答1:

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)