尝试并抓住展开线?Swift 2.0,XCode 7

Phi*_*ecz 2 xcode swift ios8 xcode7 swift2

我的代码中有以下展开行:

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

有时会出现这个致命的错误:

致命错误:在展开Optional值时意外发现nil

我知道为什么有时会出现这个错误,但有没有办法在这条线上做一个try-catch语句

Rob*_*ier 7

不,这不是尝试和捕获的目的.!意思是"如果这是零,那么崩溃." 如果你不是那个意思,那么就不要使用!(提示:你很少想使用!).使用if-letguard-let:

if let url = NSURL(string: urlString) {
    UIApplication.sharedApplication().openURL(url)
}
Run Code Online (Sandbox Code Playgroud)

如果你已经有一个try区块并希望将这种情况转变为a throw,那么这guard-let是理想的:

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)
Run Code Online (Sandbox Code Playgroud)