我在过去无数次修复了零星的 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/