如何组合数组中的元素?



我正在尝试将"角色"项目"参数具有相同"id"的对象。和";title"参数:

struct Project: Identifiable {
var id: String
var title: String
var role: String
}
var myProjects = [Project(id: "1", title: "Sunset", role: "2nd AD"),
Project(id: "2", title: "Lights", role: "Mix Tech"),
Project(id: "2", title: "Lights", role: "Sound Mixer"),
Project(id: "3", title: "Beach", role: "Producer")]
var updatedProjects: [Project] = []
// The goal is to update myProjects to show the following:
updatedProjects = [Project(id: "1", title: "Sunset", role: "2nd AD"),
Project(id: "2", title: "Lights", role: "Mix Tech & Sound Mixer"),
Project(id: "3", title: "Beach", role: "Producer"]

这就是我到目前为止所尝试的,结果是给我myProjects数组中每个项目的角色参数的重复组合。

var dupProjects = myProjects
for myProject in myProjects {
for dupProject in dupProjects {
if myProject.id == dupProject.id {
let combinedRoles = "(myProject.role) & (dupProject.role)"
updatedProjects.append(Project(id: myProject.id, 
title: myProject.title, 
role: combinedRoles))
}
}
}
print(updatedProjects) 
// [__lldb_expr_48.Project(id: "1", title: "Sunset", role: "2nd AD & 2nd AD"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Mix Tech & Mix Tech"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Mix Tech & Sound Mixer"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Sound Mixer & Mix Tech"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Sound Mixer & Sound Mixer"),
__lldb_expr_48.Project(id: "3", title: "Beach", role: "Producer & Producer")]

您可以使用字典将它们按id分组,组合角色,然后将组转换回单个Project

let combined = Dictionary(grouping: myProjects) { element in
return element.id
}.compactMapValues { projects -> Project? in
var first = projects.first
first?.role = projects.map { $0.role }.joined(separator: " & ")
return first
}.values.map { $0 }

相关内容

  • 没有找到相关文章

最新更新