xcode - ioS Swift: Unexpectedly found nil while unwrapping optional value -
while trying read contents of file var:
var mytext = "" ... println(downloadfilepath) mytext = string(contentsoffile: downloadfilepath, encoding: nsutf8stringencoding, error: nil)!
i error: unexpectedly found nil while unwrapping optional value
the file present, , generated earlier. size , contents of file may vary @ each run. same code works sometimes.
could size of file (21k) or contents - cause this?
trust me, compiler. know i'm doing. i'm taking off seatbelt , helmet.
that's tell compiler when use force-unwrap operator, !
, or deal "implicitly unwrapped optional" type such string!
. avoid @ costs. try restructuring code this:
assert(nil != (downloadfilepath string?)) var error: nserror? = nil if let mytext = string(contentsoffile: downloadfilepath, encoding: nsutf8stringencoding, error: &error) { println("contentsoffile called successfully!") println("mytext: \(mytext)") } else { println("i should implement error handling. happened? \(error)") assertionfailure("until have ui telling user fail, let's visit debugger.") }
there 2 techniques in here use keep code happy:
use assertions , preconditions. crash @ earliest sign of unrecoverable failure. dead program lot less damage crippled one, quoth pragprog tips. assertions serve executable documentation: if assert state, next programmer reading code can reason possible states in method.
until world entirely safe
nil
(which isn't if you're using foundation or introduce!
force-unwrap code), may findnil
in non-optional types error shows. if suspect this, turn non-optional optional , check it. threw few examples of how can deal these sneaky nils. combine these assertions around method calls don't express contracts in signatures.
Comments
Post a Comment