gpt4 book ai didi

arrays - 如何使用条件过滤自定义对象数组

转载 作者:行者123 更新时间:2023-11-28 08:04:40 26 4
gpt4 key购买 nike

我有项目类

 class Item {
var id:Int
var name:String
var value:Int
var isDefault:Bool
}

在 Class Item 的基础上,我有 2 个 [Item] 类数组,如果 id 匹配,我想将这个数组与第一个数组中的对象替换为第二个数组,并且应该附加(第一个/第二个)中的所有剩余数组

let fisrt = Item(id: 1, name: "A", value: 3, isDefault:false)
let second = Item(id: 2, name: "B", value:5,isDefault:false)
let third = Item(id: 3, name: "c", value:5,isDefault:false)

var fisrtArray = [fisrt, second, third]

let fisrt2 = Item(id: 4, name: "P", value: 13, isDefault:true)
let second2 = Item(id: 2, name: "Q", value:15, isDefault:true)
let third2 = Item(id: 7, name: "R", value:15, isDefault:true)
let forth2 = Item(id: 8, name: "S", value:18, isDefault:true)

var secondArray = [fisrt2, second2, third2,forth2]

所以我的结果数组应该是

Item(id: 1, name: "A", value: 3, isDefault:false)
Item(id: 2, name: "Q", value:5,isDefault:true)
Item(id: 3, name: "c", value:5,isDefault:false)
Item(id: 4, name: "P", value: 13, isDefault:true)
Item(id: 7, name: "R", value:15, isDefault:true)
Item(id: 8, name: "S", value:18, isDefault:true)

Note: size of array may be any thing either firstArray is large or Second its not dependent. I do it with for loop but i think there other way of doing it

最佳答案

let result = secondArray
result.append(contentsOf: fisrtArray.filter { item in
!secondArray.contains(where: { $0.id == item.id })
})

之后你可以按idresult进行排序

关于arrays - 如何使用条件过滤自定义对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45519997/

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