1

I am learning to do the registration using the remote sql. I only ask the user to input the email address and password, then press "register" button. The registration information will be stored in the remote database. the app build successfully. However, when i input the email address and password, then the app stops at the sentence.

    let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

saying that it has the error of

 EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). 

I also take a look at the output

 "fatal error: 'try!' expression unexpectedly raised an error:
 Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo=
 {NSDebugDescription=No value.}: file 
/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-
 700.1.101.15/src/swift/stdlib/public/core/ErrorType.swift, line 50 (lldb) ". 

I don't know how to deal with it. Please help. Thanks.

  • What is your data? You would get that error if it wasn't valid json – dan Jan 23 '16 at 18:46
  • Thank Dan. It is always good to consider the nil and the error situation. – swiftlearne Jan 23 '16 at 20:15
  • `"No value."` means that `data` is empty, not `nil`. If `data` were `nil`, you'd get [`fatal error: unexpectedly found nil while unwrapping an Optional value`](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu). Related: http://stackoverflow.com/questions/36462298/error-domain-nscocoaerrordomain-code-3840-no-value-userinfo-nsdebugdescripti – ma11hew28 Sep 20 '16 at 16:26

1 Answers1

1

When you use try with the exclamation point you are telling the compiler you don't care about the errors, and since you've done that then when you try to force cast your data, and an error occurs it will just crash instead of entering the catch block to tell you what the error is. To do this safely, and to find out potential errors, you should do this instead:

do {
    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
} catch (_) {
    //here you can get access to all of the errors that occurred when trying to serialize
}

Before doing any of this though, you should do a simple check to see if data != nil { /**try to serialize here*/ }

pbush25
  • 5,228
  • 2
  • 26
  • 35
  • Thank pbush25, you are right. After I changed to the do /catch patten. Now it works. So it is always good to be use do/catch for try, not just being lazy to use try! – swiftlearne Jan 23 '16 at 20:12
  • Yes it is and that's why Apple added it to the language! If you find that my answer worked for you, please up vote and accept it :) – pbush25 Jan 23 '16 at 20:12