Search code examples
iosswift2realmoption-typeword-wrap

Realmswift: optional wrapping error


I am trying to pass my JSON data to my realm database but I keep being thrown this error

fatal error: unexpectedly found nil while unwrapping an Optional value

at user.name = (result["name"]?.string)! but I am able to get this output when I do a 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 is my 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 as NSError {
                    print("Error with realm: " + err.localizedDescription)
                }

            }
            else
            {
                print("JSON data is nil. 123")
            }
    }

Solution

  • Optionals are capable of holding a nil value.

    ! means forced unwrap, don't use ! unless you are sure it has a value.

    Might be the problem:

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

    Remove the ! in the above lines of code.

    Try:

    if let validName = (result["name"]?.string) {
       //Will be executed only when non-nil
       user.name = validName
    }
    
    if let validAPIToken = (result["api_token"]?.string) {
       //Will be executed only when non-nil
       user.apiToken = validAPIToken
    }
    

    Documention

    Pls read about Optionals.