我试图创建一个对象,如果它不存在于数组中,并删除一个重复的对象。以下代码可以成功确定对象是否已存在以及是否重复,我不确定的是如何捕获方法内 IF 语句内的实际对象,以便能够删除重复if existanceCount == 2{}
对象contains(where:)
之一。
如何捕获contains(where:)
方法内的对象?
我基本上需要访问方法{$0}
内部contains(where:)
。
func dogCleanup(){
var existanceCount = 0
if dogs.contains(where: {$0.name == "Teddy"}){
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...")
}
}
编辑:添加了dogNames数组。
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...")
}
}
}
编辑2。
这是我所期待的上下文。
实施例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
实施例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
实施例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
实施例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
实际上,如果您始终调用此方法来按名称选择一只狗并创建一只新狗(如果它不存在),则不必检查该对象是否多次出现。