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

后端 未结 1 1062
花落未央
花落未央 2021-01-13 14:33

I have the following unwrapping line in my code:

UIApplication.sharedApplication().openURL((NSURL(string: url)!))

Sometimes there occurs this f

1条回答
  •  执笔经年
    2021-01-13 15:10

    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)
    

    0 讨论(0)
提交回复
热议问题