What is the best way to filter two Struct Arrays to match by ID and added the information in a specific property.
Example
Struct User {
let id: Int
let name: String
var arts: [Article]?
}
Struct Article {
let userId: Int
let id: Int
let title: String
let body: String
}
I have an array with all Users and other array with all Post for all Users. I need to add into User Array all post by user (User.id == Article.userId)
I’m trying to do with this.
var art = [Article]()
var users = [User]()
self?.art.forEach({ art in
guard let userId = self?.users.firstIndex(where: { $0.id == art.userId }) else {
print("Failed to find a Art by UserID")
return
}
self?.users[userId].arts?.append(art)
})
The idea is added into User Struct all Articles corresponding by user
2
Answers
I think the best possible way is to convert it to a dictionary. I think the below code is well explonary.
I think your code was in the right direction. Try this approach (works for me):