I need to extract all Posts Titles from an JSON API using another JSON API of users and after that to extract the count of comments for each Post. Here I have:
In Users I have a unique ID, in Posts I have UserID and in comments I have PostID.
For the moment I extracted all data from all three API's in three arrays. Now I need to create two functions:
getPostsTitleForSelectedUser()
getNumberOfCommentsForEachPost()
Here is a part of code:
class UserDetailsController: UIViewController {
@IBOutlet weak var detailsTableView: UITableView!
var usersArray = [User]()
var postsArray = [Post]()
var commentsArray = [Comment]()
func getPostsTitleForSelectedUser() -> String{
let postTitle: String? = "POST TITLE FOR TEST"
return postTitle!
}
func getNumberOfCommentsForEachPost() -> String{
let comments = "4131231231"
return comments
}
}
Try something like this
func getPostsTitleForSelectedUser(user: User) -> [String] {
return postsArray.filter { (post) -> Bool in
post.userId == user.id
}.map { (post) -> String in
return post.title
}
}
func getNumberOfCommentsForEachPost(post: Post) -> Int {
return commentsArray.filter { (comment) -> Bool in
comment.postId == post.id
}.count
}