swift - 如何包装函数 try catch 以便强制展开 nil 不会使应用程序崩溃?

标签 swift

当我调用的函数使用以下内容时,我经常收到这些错误:

 optionalVar!

"Unexpectedly found nil while unwrapping an Optional"

如果我不能始终控制内部代码,我不确定如何处理有时会失败的函数?

有没有办法避免此类崩溃?在大多数语言中,我可以在大多数事情上放置 try catch。

当我做类似的事情时:

if let result = Blah.someExternalFunction(html: "some bad html") { } 

即使在尝试添加 try? 后,这仍然可能在“someExternalFunction”内失败。在它前面。

谢谢

最佳答案

您要寻找的是if let

如果您有一个可选值,您可以简单地执行以下操作来“尝试”它:

if let val = optionalVar{
    //val is already unwrapped
}
else{//it was nil}

另一种选择是使用 guard 语句。其工作原理类似。

guard let val = optionalVar 
else{
    //the value is nil, so you need to exit the current function
    return
}
//'val' is now unwrapped for any code below the guard-else statement

关于swift - 如何包装函数 try catch 以便强制展开 nil 不会使应用程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594590/

相关文章:

ios - 在 Swift 中链接到 iTunes 音乐

ios - 使用批处理在 Firestore 内增加值 - "Ambiguous use of ' 增量'"

ios - Swift 3 Horizo​​ntal Multiple UIScrollView - 不同的速度

swift - 类型 'String' 的值不符合预期的字典值类型 'AnyObject'

ios - UITextField 填充

swift - UILabel 中使用 NSAttributedString 的 HTML 文本(带表格)

ios - 自定义分段控件宽度代码没有故意工作

swift - 在 swift 中为 UIBarButtonItem 设置背景图像

ios - 如何为 UITextView 中的特定单词设置样式?

ios - Realm Swift 更改命名变量的数据类型