swift - 调试 nil 选项

标签 swift

我在过去无数次修复了零星的 unexpectedly found nil while unwrapping an Optional value 错误,现在我刚刚修复了一个;然而,我现在的做法是通过断点猜测 nil 选项的位置。

总是 Swift._fatalErrorMessage(在程序集中)下有一个EXC_BREAKPOINT 当我抛出这样的错误时。

是否有更有效的方法(如异常捕获)跳转到 nil 可选而不是猜测它与日志消息和(内联)断点的位置?

最佳答案

您的崩溃几乎肯定发生在您使用 ! 强行解包可选的行中。除非您绝对确定某个值存在,否则您应该改用 if let

代替:

let myValue = myArray[index]!  // will crash if myArray[index] is nil

使用这个:

if let myValue = myArray[index] {
  println("myValue has a value and it is \(myValue)")
  // Code using myValue
} else {
  println("myValue is nil")
}

编辑:要直接回答您的问题,请搜索 ! 的实例,通常将它们替换为 if let?

关于swift - 调试 nil 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29223886/

相关文章:

ios - 未调用 UILabel 子类中的 UIGestureRecognizer

ios - Swift 中的可选 ("nil") 是什么意思?

ios - 消除 Swift 中重复的 'user defined runtime attribute' 代码

swift - 如何在 swift4 的字典中获取 'keys in an array' 的值

iOS 导航栏不够半透明

ios - 从 Appdelegate 实例化 View Controller

ios - 自动登录 Firebase 用户

ios - 在 MFMessageComposeViewController 上设置 NavigationBar 背景颜色

ios - 在 Swift 中,使用选择器 init 覆盖的方法具有不兼容的类型

ios - 在异步调用完成后如何运行代码并且代码在 swift 3 中的异步函数之外