简体   繁体   English

Realmswift:可选包装错误

[英]Realmswift: optional wrapping error

I am trying to pass my JSON data to my realm database but I keep being thrown this error 我正在尝试将JSON数据传递到我的领域数据库,但我一直被抛出此错误

fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil

at user.name = (result["name"]?.string)! user.name = (result["name"]?.string)! but I am able to get this output when I do a print(result) 但是我print(result)时能够得到这个输出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")
            }
    }

Optionals are capable of holding a nil value. 可选函数可以保留nil值。

! 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. 请阅读有关可选的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM