Reputation: 8705
While trying to read contents of a file into a var:
var mytext = ""
...
println(downloadFilePath)
mytext = String(contentsOfFile: downloadFilePath, encoding: NSUTF8StringEncoding, error: nil)!
I get this error: Unexpectedly found nil while unwrapping optional value
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?
Upvotes: 0
Views: 953
Reputation: 7351
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!
. 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. 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.
Upvotes: 1