You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中如何基于另一对象数组过滤出不匹配ID的元素

在Swift 4中过滤数组的解决方案

嘿,这个需求用Swift的高阶函数就能轻松实现,我给你两种实用的写法,按需选择就行~

步骤1:定义对应的数据结构

首先我们需要把你给出的数组元素转成Swift里的结构体(当然用类也可以,结构体作为值类型更适合这种场景):

struct ArrayOneItem {
    let keyphraseId: String
    let name: String
}

struct ArrayTwoItem {
    let idstring: String
    let name: String
}

步骤2:创建示例数组

按照你给出的内容初始化两个数组:

let arrayOne: [ArrayOneItem] = [
    ArrayOneItem(keyphraseId: "tcpid1234", name: "shakti"),
    ArrayOneItem(keyphraseId: "tcpid456", name: "shakti"),
    ArrayOneItem(keyphraseId: "tcpid897", name: "srichandan "),
    ArrayOneItem(keyphraseId: "tcpid779", name: "prakash")
]

let arrayTwo: [ArrayTwoItem] = [
    ArrayTwoItem(idstring: "tcpid1234", name: "shakti"),
    ArrayTwoItem(idstring: "tcpid456", name: "shakti")
]

步骤3:过滤数组(推荐高效写法)

我们先把arrayTwo里的idstring提取成一个Set——因为集合的contains方法是O(1)的时间复杂度,比数组的O(n)快很多,数据量大的时候优势明显:

// 提取需要排除的ID集合
let excludedIds = Set(arrayTwo.map { $0.idstring })
// 过滤arrayOne,保留不在排除集合里的元素
let filteredArray = arrayOne.filter { !excludedIds.contains($0.keyphraseId) }

备选写法(简单但效率稍低)

如果你的arrayTwo元素很少,也可以直接用数组来判断,写法更直观:

// 提取需要排除的ID数组
let excludedIdArray = arrayTwo.map { $0.idstring }
// 过滤数组
let filteredArray2 = arrayOne.filter { !excludedIdArray.contains($0.keyphraseId) }

运行以上代码后,filteredArray里就会剩下keyphraseId为tcpid897和tcpid779的两个元素,完全符合你的需求~

内容的提问来源于stack exchange,提问作者Shakti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:49