I'm trying to create an object if it doesn't exist in an array and delete one if it's duplicated. The following code can successfully determine if an object already exists and if it's duplicated, what I'm not sure about is how to capture the actual object inside the IF statement if existanceCount == 2{}
within the contains(where:)
method to be able to delete one of the duplicate objects.
How can I capture an object inside the contains(where:)
method?
I basically need to access {$0}
inside the contains(where:)
method.
func dogCleanup(){
let dogNames = ["Teddy","Browny","Mia"]
var existanceCount = 0
for i in 0..<dogNames.count{
if dogs.contains(where: {$0.name == dogNames[i]}){
existanceCount += 1
if existanceCount == 2{
print("Dog exists 2 times, delete it")
// how can I capture one of the duplicate objects
}
}else{
print("Does NOT exist, add dog...")
}
}
}
Here is in context what I'm expecting after calling the dogCleanup() method.
Example 1
let dogs = [Dog(name: "Teddy"), Dog(name: "Browny"),Dog(name: "Mia")] // objects in Core Data
let dogNames = ["Teddy","Browny","Mia"] // default dog names
func dogCleanup(){
// do nothing, both match
}
// What I'm expecting after running the dogCleanup
Teddy,Browny,Mia
Example 2
let dogs = [Dog(name: "Teddy"), Dog(name: "Browny")] // objects in Core Data
let dogNames = ["Teddy","Browny","Mia"]
func dogCleanup(){
// add Mia since it doesn't exist in Core Data
}
// What I'm expecting after running the dogCleanup
Teddy, Browny, Mia
Example 3
let dogs = [Dog(name: "Teddy"), Dog(name: "Browny"), Dog(name: "Browny")] // objects in Core Data
let dogNames = ["Teddy","Browny","Mia"] // default dog names
func dogCleanup(){
// delete one Browny and add Mia since it doesn't exist in Core Data
}
// What I'm expecting after running the dogCleanup
Teddy, Browny, Mia
Example 4
let dogs = [Dog(name: "Teddy"), Dog(name: "Browny"), Dog(name: "Browny"), Dog(name: "Shadow")] // objects in Core Data
let dogNames = ["Teddy","Browny","Mia"] // default dog names
func dogCleanup(){
// delete one Browny, add Mia and leave Shadow
}
// What I'm expecting after running the dogCleanup
Teddy, Browny, Mia, Shadow