swift 判断数组是否含有改对象元素,有就更新,没有就添加
class YourModel {
var id: Int
var name: String
// 其他属性
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
// 示例方法
func addOrUpdateModel(modelToUpdate: YourModel, in modelsArray: inout [YourModel]) {
if let index = modelsArray.firstIndex(where: { $0.id == modelToUpdate.id }) {
// 如果找到具有相同ID的对象,更新它
modelsArray[index] = modelToUpdate
} else {
// 如果未找到具有相同ID的对象,添加新对象
modelsArray.append(modelToUpdate)
}
}
// 示例用法
var modelsArray: [YourModel] = []
let model1 = YourModel(id: 1, name: "Model 1")
addOrUpdateModel(modelToUpdate: model1, in: &modelsArray)
let model2 = YourModel(id: 2, name: "Model 2")
addOrUpdateModel(modelToUpdate: model2, in: &modelsArray)
let updatedModel1 = YourModel(id: 1, name: "Updated Model 1") // 具有相同ID
addOrUpdateModel(modelToUpdate: updatedModel1, in: &modelsArray) // 更新具有相同ID的对象
print(modelsArray)