gpt4 book ai didi

ios - 更新数组内的自定义对象而不重新初始化

转载 作者:行者123 更新时间:2023-11-30 10:58:16 25 4
gpt4 key购买 nike

 class Person {
var firstName: String?
var lastName: String?
var age: String?

init(_ firstName:String, lastName:String, age:String) {
self.firstName = firstName
self.lastName = lastName
self.age = age
}
}

我有一个 Person 类数组。

var arrayper = [Person]()

let person1 = Person("test1", lastName: "test1last", age: "20")
arrayper.append(person1)

let person2 = Person("test2", lastName: "test2last", age: "20")
arrayper.append(person2)

let person3 = Person("mock", lastName: "mock", age: "20")
arrayper.append(person3)

print(arrayper.filter({$0.firstName!.starts(with: "te")}))

现在我只想要名字和姓氏,但名字以“te”开头。并且还在运行时删除年龄属性。我知道如何按名称排序。但不知道如何从数组对象中删除年龄!我不想创建另一个对象并替换为新对象。

任何建议或更好的方法。提前致谢!

最佳答案

你可以这样尝试

filtered = arrayper.filter({$0.firstName!.starts(with: "te")})


class PersonName {
var firstName: String = ""
var lastName: String = ""

init(_ firstName:String, lastName:String) {
self.firstName = firstName
self.lastName = lastName
}
}

var personNames: [PersonName] = [] // Initialize
filtered.forEach { (personDetail) in
personNames.append( PersonName(personDetail.firstName ?? "", lastName: personDetail.lastName ?? "")) // Filtered values append to array
}

//打印输出

personNames.forEach { (personName) in
print(personName.firstName)
print(personName.lastName)

}

关于ios - 更新数组内的自定义对象而不重新初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700830/

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