Home > Back-end >  How to create one object or array with data from 2 network calls Swift
How to create one object or array with data from 2 network calls Swift

Time:01-24

I have 2 network calls, one for user and one for posts. User have id and name properties, Post have userId and title properties. I have populated data in 2 separate arrays, fetchedUsers and fetchedPosts.

I need to show in tableViewCell username and post(title) So Post userId needs to grab User id

If my explanation not clear, pls ask, i try to explain :)

Thanks in advice for help!

    struct User: Codable {
    let id: Int
    let name: String
}

    struct Post: Codable {
    let userId: Int
    let title: String
}

JSON:

    Post:
    {
    "userId": 1,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut"
   }

    User:
{
"id": 8,
"name": "Nicholas Runolfsdottir V",
  }

CodePudding user response:

You have to combine 'Post' and 'User' models into one. (for example 'UserPost') First, get the Post arrays from the network call and create the 'UserPost' array, then fill the userName inside the PostModel from the User array.

Your Model will be something like this:

struct UserPost {
    var userId: Int
    var userName: String?
    var postTitle: String
}
  •  Tags:  
  • Related