A better way to do these parsings of Json to Model and vice versa is by using any parsing library e.g. ObjectMapper, SwiftyJson or swift's Codable protocol. You can do both way parsing with such an ease with them and even for complex data model you don't have to do a lot of work.
So better not to reinvent the wheel.
Here are some examples for your specific usecase.
let userData = ["lastname": "Last", "firstname": "First"]
Using ObjectMapper: (Install pod and add the import to get it work)
struct User: Mappable {
var firstname: String?
var lastname: String?
init?(map: Map) {}
mutating func mapping(map: Map) {
firstname <- map["firstname"]
lastname <- map["lastname"]
}
}
if let newuser = Mapper<User>().map(JSON: userData) {
print(newuser)
}
Using Codeable protocol:
struct User: Codable {
var firstname: String
var lastname: String
}
do {
let data = try JSONSerialization.data(withJSONObject: userData, options: .prettyPrinted)
let decoder = JSONDecoder()
let user = try decoder.decode(User.self, from: data)
} catch {
print(error.localizedDescription)
}