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

iOS中搜索字典嵌套模型数组问题求助(Swift)

解决Swift中字典数组嵌套模型数组的搜索问题

嘿,我来帮你搞定这个搜索的问题~

先说说你代码里出错的原因:你在第二层filter里拿到的参数是整个[MerchantModel]数组,而不是单个MerchantModel实例,自然没法直接访问nameString属性啦。咱们需要再深入一层,检查数组里的每个模型是否符合条件。

根据你的需求,我给你两种常见的实现方案:

方案1:保留包含符合条件模型的整个字典项

如果你想的是「只要某个字典里存在符合搜索条件的商家模型,就完整保留这个字典项(包括里面所有模型)」,可以这么写:

func filter(array: [[String: [MerchantModel]]], byString filterString: String) -> [[String: [MerchantModel]]] {
    return array.filter { dictItem in
        // 检查当前字典里的所有商家数组,是否存在符合条件的模型
        dictItem.values.contains { merchantArray in
            merchantArray.contains { merchant in
                merchant.nameString == filterString
                // 如果要支持模糊搜索(比如包含关键词、忽略大小写),可以改成:
                // merchant.nameString.localizedCaseInsensitiveContains(filterString)
            }
        }
    }
}

方案2:过滤字典项,只保留符合条件的模型

如果你想的是「不仅保留有符合条件模型的字典项,还要把每个字典里的商家数组过滤成只包含符合条件的模型(没有符合的就去掉整个字典项)」,可以用这个版本:

func filter(array: [[String: [MerchantModel]]], byString filterString: String) -> [[String: [MerchantModel]]] {
    return array.compactMap { dictItem in
        // 对字典里的每个商家数组进行过滤,只留下符合条件的模型
        let filteredDict = dictItem.mapValues { merchantArray in
            merchantArray.filter { $0.nameString == filterString }
        }
        // 只有当过滤后的字典里存在非空的商家数组时,才保留这个字典项
        return filteredDict.values.contains { !$0.isEmpty } ? filteredDict : nil
    }
}

这两个方案都没有用for/while循环,完全用Swift的高阶函数实现,符合你的要求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:03:32