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

Swift数组筛选:判断任意元素存在于另一数组的正确实现

数组交集筛选实现方案

你原代码的问题出在for循环内首次迭代就触发return,仅校验了cat数组的第一个元素,未完成全量遍历,自然无法正确判断两个数组是否存在公共元素。

推荐高效实现(基于Set)

利用Swift标准库提供的集合交集判断方法实现,时间复杂度更低,适合绝大多数场景:

@Published var filteredCats: [Int] = []

func filterByInt(array: [Item]) -> [Item] {
    // 未选择任何筛选项时,默认返回全部元素,符合通用筛选交互逻辑
    guard !filteredCats.isEmpty else { return array }
    let filterSet = Set(filteredCats)
    return array.filter { item in
        guard let cats = item.cats else { return true }
        // isDisjoint(with:) 返回true代表两个集合无公共元素,取反后即为存在交集的判断
        return !Set(cats).isDisjoint(with: filterSet)
    }
}

纯数组遍历实现

如果不想引入Set类型,也可以通过修正循环逻辑实现,只要遍历到任意匹配值就提前返回true,全量遍历无匹配再返回false:

@Published var filteredCats: [Int] = []

func filterByInt(array: [Item]) -> [Item] {
    guard !filteredCats.isEmpty else { return array }
    return array.filter { item in
        guard let cats = item.cats else { return true }
        for cat in cats {
            if filteredCats.contains(cat) {
                return true
            }
        }
        return false
    }
}

逻辑验证

用你给出的测试用例校验,当筛选条件为[0, 3, 4]时:

  • cat为[1,2,3]:存在公共元素3 → 保留
  • cat为[2,3]:存在公共元素3 → 保留
  • cat为[]:无公共元素 → 过滤
  • cat为[5,6,7]:无公共元素 → 过滤
    返回结果完全符合「存在公共交集即保留」的需求。

性能选择提示:待筛选条目量大于100条时优先选择Set实现,集合的元素查找时间复杂度为O(1),远快于数组的O(n)遍历查找。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:21:28