ios - Realmswift: optional wrapping error -


i trying pass json data realm database keep being thrown error

fatal error: unexpectedly found nil while unwrapping optional value

at user.name = (result["name"]?.string)! able output when print(result)

particulars { "name" : "jonny walker", "api_token" : "qwertyuiop1234567890", "profile_picture" : "http:default_profile_picture.jpg", "id" : 10, "email" : "jwalker@gmail.com" "username" : "jonny" } 

this code:

alamofire.request(.post, data.loginendpoint, parameters: parameters)         .responseobject { (response: response<particulars, nserror>) in              if let result = response.result.value             {                  do{                     print(realm.configuration.defaultconfiguration.fileurl)                     print(result)                     let user = particulars()                     let realm = try realm()                     user.name = (result["name"]?.string)!                     user.apitoken = (result["api_token"]?.string)!                     try realm.write() {                         realm.add(user, update: true)                     }                 }                  catch let err nserror {                     print("error realm: " + err.localizeddescription)                 }              }             else             {                 print("json data nil. 123")             }     } 

optionals capable of holding nil value.

! means forced unwrap, don't use ! unless sure has value.

might problem:

user.name = (result["name"]?.string)! user.apitoken = (result["api_token"]?.string)! 

remove ! in above lines of code.

try:

if let validname = (result["name"]?.string) {    //will executed when non-nil    user.name = validname }  if let validapitoken = (result["api_token"]?.string) {    //will executed when non-nil    user.apitoken = validapitoken } 

documention

pls read optionals.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -