gpt4 book ai didi

swift - 将多个对象的属性合并为一个

转载 作者:行者123 更新时间:2023-11-30 12:35:45 25 4
gpt4 key购买 nike

假设我有这门课:

class Person {
var firstName: String!
var lastName: String!
var phoneNumber: String?
var email: String?
var address: String?
}

现在我实例化这个:

let person1 = Person()
person1.firstName = "Nicolas"
person1.lastName = "Cage"
person1.phoneNumber = "999-999-999"
person1.address = "No 123, NYC"

let person2 = Person()
person2.firstName = "Nicolas"
person2.lastName = "Cage"
person2.phoneNumber = "123-1234-1234"
person2.address = "No 123, NYC"
person2.email = "nicolas@nicolas.com"

let person3 = Person()
person3.firstName = "John"
person3.lastName = "Travolta"

我有这个数组:

let actors: [Person] = [person1, person2, person3]

如何在不存在冲突的情况下组合/合并重复的人员,并且还具有冲突属性的列表?

合并后 Nicoals Cage 的预期属性值:

Nicolas
Cage
phoneNumber -> Conflict
No 123, NYC
nicolas@nicolas.com

最佳答案

private func merge(actors:[Person]) -> [Person] {

var uniqueActors = [Person]()
var duplicatedActors = [Person]()

//split actors into arrays
for actor in actors {
if uniqueActors.contains(where: { $0.firstName == actor.firstName &&
$0.lastName == actor.lastName}) {
duplicatedActors.append(actor)
} else {
uniqueActors.append(actor)
}
}

//merge duplicated into unique
for duplicatedActor in duplicatedActors {
let uniqueActor = uniqueActors.filter({ $0.firstName == duplicatedActor.firstName &&
$0.lastName == duplicatedActor.lastName }).first
if let uniqueActor = uniqueActor {
uniqueActor.phoneNumber = self.mergeProperty(valueOne: uniqueActor.phoneNumber, valueTwo: duplicatedActor.phoneNumber)
uniqueActor.address = self.mergeProperty(valueOne: uniqueActor.address, valueTwo: duplicatedActor.address)
uniqueActor.email = self.mergeProperty(valueOne: uniqueActor.email, valueTwo: duplicatedActor.email)
}
}

return uniqueActors

}

//merge properties of 2 objects
private func mergeProperty(valueOne: String?, valueTwo: String?) -> String? {
var isFirstPropertyExist = false
var isSecondPropertyExist = false

if let valueOne = valueOne, valueOne != "" {
isFirstPropertyExist = true
}

if let valueTwo = valueTwo, valueTwo != "" {
isSecondPropertyExist = true
}

var mergedValue : String?

switch (isFirstPropertyExist, isSecondPropertyExist) {
case (true, true):
if valueOne != valueTwo {
mergedValue = "Conflict"
//here you can print or throw an Error
} else {
mergedValue = valueOne
//random (equal values)
}

case (true, false):
mergedValue = valueOne
case (false, true):
mergedValue = valueTwo
case (false, false):
mergedValue = ""
//or you can return nil
}

return mergedValue
}

我想它可以帮助你。您可以将 func mergeProperty 传递到 Person 类的扩展中,并将 func merge 传递到 Array 类的扩展中,其中对象是 Person

关于swift - 将多个对象的属性合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42884895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com