I want to group an array of structs only using arrays into an array of new structs. In this example I want to group the Person
structs by Job
and put them in new Department
structs and put them in an array.
enum Job {
case developer
case programmer
case coder
}
struct Person {
let id: Int
let job: Job
}
struct Department {
let job: Job
var staff: [Person]
mutating func addStaff(_ person: Person) {
staff.append(person)
}
}
let initial = [
Person(id: 0, job: .developer),
Person(id: 1, job: .developer),
Person(id: 2, job: .programmer),
Person(id: 3, job: .programmer),
Person(id: 4, job: .coder)
]
func combinator(accumulator: [Department], current: Person) -> [Department] {
var accumulator = accumulator
if let index = accumulator.index(where: { $0.job == current.job }) {
var department = accumulator[index]
department.staff.append(current)
accumulator[index] = department
} else {
accumulator.append(Department(job: current.job, staff: [current]))
}
return accumulator
}
var departments: [Department] = initial.reduce([], combinator)
I feel like the if statement in the combinator(accumulator:current:)
function is a bit clunky, is there a better way to write that part or any other part of this piece of code?