So, you have an array of City objects, each with a name and an array of Business objects. You want to have it so that cities with the same name (duplicates) are merged together, along with their businesses.
Example:
let business1 = Business(name: "Business 1")
let business2 = Business(name: "Business 2")
let business3 = Business(name: "Business 3")
let business4 = Business(name: "Business 4")
// before
let cities = [
City(name: "City 1", businesses: [business1, business2]),
City(name: "City 2", businesses: [business1, business2]),
City(name: "City 1", businesses: [business3, business4])
]
// after
let cities = [
City(name: "City 1", businesses: [business1, business2, business3, business4]),
City(name: "City 2", businesses: [business1, business2])
]
If this is correct, then we can keep going.
Something like this can work:
// make City Equatable using only its name
// this is how the example differentiates between two cities
struct City: Equatable {
...
static func == (lhs: City, rhs: City) -> Bool {
lhs.name == rhs.name
}
}
// this is the cities array without duplicate cities and with merged businesses
let newCities: [City] = cities.reduce([]) { result, city in
var newResult = result
if let index = result.firstIndex(of: city) {
// gets messy with optionals
newResult[index].businesses?.append(contentsOf: city.businesses ?? [])
} else {
newResult.append(city)
}
return newResult
}
Hopefully, this will work for your use case.