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
CodePudding user response:
class Article {
let userId: Int
let id: Int
let title: String
let body: String
}
class User {
let id: Int
let name: String
var arts: [Post]?
}
I think the best possible way is to convert it to a dictionary. I think the below code is well explonary.
var dict = [Int: [Article]]()
var arts = [Article]()
for art in arts {
dict[art.userId, default: []].append(art)
}
var users = [User]()
for case let user in users {
let articles = dict[user.id]
user.atrs = articles
}
CodePudding user response:
the variable users is used to contain elements of type Article?
CodePudding user response:
I think your code was in the right direction. Try this approach (works for me):
var arts = [Article(userId: 1, id: 1, title: "title1"),
Article(userId: 6, id: 1, title: "title6")]
var users = [User(id: 1, name: "user1"),
User(id: 2, name: "user2")]
print("---> before users: \n \(users)")
arts.forEach{ art in
if let userNdx = users.firstIndex(where: { $0.id == art.userId }) {
if let _ = users[userNdx].arts {} else {
users[userNdx].arts = []
}
users[userNdx].arts!.append(art)
}
}
print("\n---> after users: \n \(users)")