试着绕过展开线? Swift2.0,XCode7
Try and catch around unwrapping line? Swift 2.0, XCode 7
我的代码中有以下展开行:
UIApplication.sharedApplication().openURL((NSURL(string: url)!))
有时会出现这个致命错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
我知道为什么有时会出现此错误,但是有没有办法围绕这一行try - catch 语句?
不,这不是 try 和 catch 的目的。 !
表示 "if this is nil, then crash." 如果您不是这个意思,则不要使用 !
(提示:您很少想使用 !
)。使用 if-let
或 guard-let
:
if let url = NSURL(string: urlString) {
UIApplication.sharedApplication().openURL(url)
}
如果您已经有一个 try
障碍并且想将这种情况变成 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)
我的代码中有以下展开行:
UIApplication.sharedApplication().openURL((NSURL(string: url)!))
有时会出现这个致命错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
我知道为什么有时会出现此错误,但是有没有办法围绕这一行try - catch 语句?
不,这不是 try 和 catch 的目的。 !
表示 "if this is nil, then crash." 如果您不是这个意思,则不要使用 !
(提示:您很少想使用 !
)。使用 if-let
或 guard-let
:
if let url = NSURL(string: urlString) {
UIApplication.sharedApplication().openURL(url)
}
如果您已经有一个 try
障碍并且想将这种情况变成 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)