xcode - 尝试捕获展开的线吗? swift 2.0、XCode 7

标签 xcode swift ios8 swift2 xcode7

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

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

有时会出现这样的 fatal error :

fatal error: unexpectedly found nil while unwrapping an Optional value

我知道为什么有时会发生此错误,但是有没有办法在这一行周围创建一个 try - catch 语句

最佳答案

不,这不是 try 和 catch 的用途。 ! 表示“如果为零,则崩溃”。如果您不是这个意思,那么就不要使用 ! (提示:您很少想使用 !)。使用 if-letguard-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/

相关文章:

ios - Audiokit:如何在 Audiobus 面板覆盖层中添加开始/停止按钮及其功能?

arrays - Swift - 数组[任何索引]?

ios - 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout

iphone - 从txt列表文件中读取并在ios中设置许多对象

objective-c - IBOutletCollection 在 Interface Builder 中设置排序

ios - 我可以在我的 iOS 应用程序中使用实验性 WebKit 功能吗?

ios - 如何提供适用于不同布局的比例自动布局值?

ios - 通过搜索 LinkedIn 获取公开资料 URL

swift - 您不能在类中使用静态方法/变量的原因是什么

ios - iOS8 的 UIAlertController 标题始终为 nil