Search code examples
swiftuikitalamofire

How should I assign my data models to map the JSON using Alamofire?


I am new to this, so I made some models for mapping JSON but early there are was some models to display templates, now I am going to display some real content on the views instead using Alamofire. It might be stupid, but how should I assign/replace the data models to make it work correctly? Here is the get method:

friendsAPI.getFriends { [weak self] users in
                 self?.friends0 = users!  // here is the crash happens because there are two different data models - `FriendModel` and `UserModel`
                 self?.tableView.reloadData()
                 print(users)
             }

There are UserModel I have used to display some content on the different views:

struct UserModel: Equatable {
    static func == (lhs: UserModel, rhs: UserModel) -> Bool {
        lhs.userSurname == rhs.userSurname
    }
    
    let userFirstName: String
    let userSurname: String
    let userPhoto: UIImage?
    var userPhotos: [UIImage]
    let userAge: Int
    let id: Int
}

And now there are FriendModel using to parse JSON:

// MARK: - FriendsResponse
 
 class FriendsResponse: Codable {
     let response: FriendsModel
 }

 // MARK: - Response

 class FriendsModel: Codable {
     let count: Int
     let items: [FriendModel]
 }

 // MARK: - Item

 class FriendModel: Codable {
     let id: Int
     let lastName, trackCode, firstName: String
     let photo100: String

     enum CodingKeys: String, CodingKey {
         case id
         case lastName = "last_name"
         case trackCode = "track_code"
         case firstName = "first_name"
         case photo100 = "photo_100"
     }
 }

In the most of my app I have used UserModel to handle and display content. So, how should I assign this data models? P.S.: I'll be so glad if someone will help me! Thank you!


Solution

  • Add a method to convert from FriendModel to UserModel:

    struct UserModel {
        init(friend: FriendModel) {
            id = friend.id
            userFirstName = friend.firstName
            userSurname = friend.lastName
            ... // assign all the other fields as needed
        }
    }
    

    Then use it to convert your results:

    friendsAPI.getFriends { [weak self] apiFriends in
        self?.friends0 = apiFriends.map({ UserModel(friend: $0) })
    }
    

    Here it is an init method, but feel free to put it in a normal func like func userFromFriend(_ friend: FriendModel) -> UserModel, and put that func wherever you want.