简体   繁体   English

ioS Swift:在展开可选值时意外找到nil

[英]ioS Swift: Unexpectedly found nil while unwrapping optional value

While trying to read contents of a file into a var: 尝试将文件内容读入var时:

var mytext = ""
...
println(downloadFilePath)
mytext = String(contentsOfFile: downloadFilePath, encoding: NSUTF8StringEncoding, error: nil)!

I get this error: Unexpectedly found nil while unwrapping optional value 我收到此错误: 展开可选值时意外发现nil

The file itself is present, and it is generated earlier. 该文件本身存在,并且它是较早生成的。 The size and contents of the file may vary at each run. 每次运行时文件的大小和内容可能会有所不同。 The same code works sometimes. 相同的代码有时可以工作。

Could it be size of the file (21K) or contents - which cause this? 可能是文件大小(21K)或内容-造成此情况的原因?

Trust me, compiler. 相信我,编译器。 I know what I'm doing. 我知道我在做什么 I'm taking off my seatbelt and helmet. 我要脱下安全带和头盔。

That's what you tell the compiler when you use the force-unwrap operator, ! 这就是在使用强制展开运算符时告诉编译器的内容! , or deal with an "implicitly unwrapped optional" type such as String! ,或处理“隐式展开的可选”类型,例如String! . This is something I avoid at all costs. 我不惜一切代价避免这样做。 Try restructuring your code like this: 尝试像这样重组代码:

assert(nil != (downloadFilePath as String?))
var error: NSError? = nil
if let mytext = String(contentsOfFile: downloadFilePath, encoding: NSUTF8StringEncoding, error: &error) {
    println("contentsOfFile was called successfully!")
    println("mytext: \(mytext)")
} else {
    println("I should implement error handling. What happened? \(error)")
    assertionFailure("Until I have a UI for telling the user about the fail, let's just visit the debugger.")
}

There are two techniques in here that I use to help keep my code happy: 在这里,我使用两种技术来使我的代码保持快乐:

  • Use your assertions and preconditions . 使用您的断言前提条件 Crash at the earliest sign of unrecoverable failure. 最早出现无法恢复的故障时会崩溃。 A dead program normally does a lot less damage than a crippled one, quoth the PragProg Tips . 程序失效通常比残废程序造成的损害小得多 Assertions also serve as executable documentation: If you assert a certain state, the next programmer reading your code can reason about possible states in your method. 断言也可用作可执行文档:如果断言某个状态,则下一个读取代码的程序员可以推断出方法中可能的状态。

  • Until your world is entirely safe from nil (which it isn't if you're using Foundation or introduce a ! force-unwrap into your code), you may find nil in non-optional types as the error shows. 直到您的世界完全远离nil (如果您使用Foundation或在代码中引入! force-unwrap才是安全的),您可能会在错误显示的非可选类型中找到nil If you suspect this, turn the non-optional into an optional and check it. 如果您怀疑这一点,请将非可选项变成可选项并进行检查。 I threw together a few examples of how you can deal with these sneaky nils. 我汇总了一些示例 ,说明如何处理这些偷偷摸摸的指甲。 Combine these with assertions around method calls that don't express their contracts in their signatures. 将这些与围绕未在其签名中表示其合同的方法调用的断言相结合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM