Hajar ELKOUMIKHI
Hajar ELKOUMIKHI

Reputation: 92

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

Upvotes: 0

Views: 44

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

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

Upvotes: 1

Related Questions