我的代码中有以下展开行:
UIApplication.sharedApplication().openURL((NSURL(string: url)!))
有时会出现这样的 fatal error :
fatal error: unexpectedly found nil while unwrapping an Optional value
我知道为什么有时会发生此错误,但是有没有办法在这一行周围创建一个 try - catch 语句?
最佳答案
不,这不是 try 和 catch 的用途。 !
表示“如果为零,则崩溃”。如果您不是这个意思,那么就不要使用 !
(提示:您很少想使用 !
)。使用 if-let
或 guard-let
:
if let url = NSURL(string: urlString) {
UIApplication.sharedApplication().openURL(url)
}
如果您已经有一个 try
block ,并且希望将这种情况转变为 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)
关于xcode - 尝试捕获展开的线吗? swift 2.0、XCode 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40549633/