-1

Im using Firestore and when I request data, it comes in an array

print("Document data: \(dataDescription)")

which prints out Document data: ["lastname": Test, "firstname": Test]

I created a class 

    class User {

    var firstName: String
    var lastName: String

    init(firstName: String, lastName: String) {

        self.firstName = firstName
        self.lastName = lastName
    }

}

How can I assign the part of the array for "lastname" to the User class and assign in to lastName

dawis11
  • 820
  • 1
  • 9
  • 24
equ1nox
  • 87
  • 8

2 Answers2

1

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)
}
Najeeb ur Rehman
  • 403
  • 4
  • 11
0

This

["lastname": Test, "firstname": Test]

is a dictionary not an array , you need

guard let res = snap.value as? [String:String] ,let fname = res["firstName"] ,     
let lname = res["lastName"] else { return }
let user = User(firstName:fname,lastName:lname) 

Tip:think if you really need a struct not class

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87