简体   繁体   中英

saving data in a swift model

I have a user model defined as follows :

class UserModel: NSObject {

var firsname: String?
var lastname: String?
var mail: String?

}

and in one of my http requests, I'm catching the json response as :

guard let mail = jsonArray[0]["mail"] as? String else { return }

So when I print the mail print(mail) it works fine and prints the correct mail string, but when I try to save that email in my user attributes, it gives me a nil value.

guard let mail = jsonArray[0]["mail"] as? String else { return }
    self.user?.mail = mail
    if let mailUnwrapped = self.user?.mail {
    print(mailUnwrapped)     // prints nil 
    }

am I missing something ? Any help please ! Thank you

You might need to initialise user first before setting it's properties. Try:

// First
self.user = UserModel()
// Then
guard let mail = jsonArray[0]["mail"] as? String else { return }
self.user?.mail = mail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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