I have two arrays (both County and City are conformed to Comparable):
let array1 = [
Country(code: "US", cities: [
City(name: "Dallas"),
City(name: "New York")
]),
Country(code: "UK", cities: [
City(name: "London"),
City(name: "Manchester")
])
]
let array2 = [
Country(code: "DE", cities: [
City(name: "Munich"),
City(name: "Leipzig")
]),
Country(code: "US", cities: [
City(name: "Seattle")
City(name: "New York")
]),
Country(code: "UK", cities: [
City(name: "London"),
City(name: "Birmingham"),
City(name: "Manchester")
])
]
So far I managed to combine those only comparing country codes:
let mergedArray = array1 + array2.filter { country in
return !array1.contains { $0.code == country.code }
}
How do I account for those repeated cities inside? Basically to get this:
let mergedArray = [
Country(code: "DE", cities: [
City(name: "Munich"),
City(name: "Leipzig")
]),
Country(code: "US", cities: [
City(name: "Dallas"),
City(name: "Seattle")
City(name: "New York")
]),
Country(code: "UK", cities: [
City(name: "London"),
City(name: "Birmingham"),
City(name: "Manchester")
])
]
Tried also (isn't adding those extra cities for UK):
func combine<T>(_ arrays: Array<T>?...) -> Set<T> {
return arrays.compactMap{$0}.compactMap{Set($0)}.reduce(Set<T>()){$0.union($1)}
}
and tried this but no luck at all (a lot of duplicates):
let mergedArray = array1 + array2.filter { country in
return !array1.contains { $0.code == country.code } ||
(!array1.contains(where: { $0.cities?.contains(where: country.cities!.contains) as! Bool }))
}
array1using aForEachand for all countries matching the code insidearray2just add the city objects into theCountryobject inarray1. Append all the "non-matching" country codes at the endforandifbut that wouldn't be fun :)