gpt4 book ai didi

swift - 从字符串数组中获取新的字典数组,以在 Collection View 中显示

转载 作者:搜寻专家 更新时间:2023-11-01 06:59:35 25 4
gpt4 key购买 nike

假设我有这样一组字典:

[
["name": "Jack", "age": 20],
["name": "Molly", "age": 21],
["name": "Kyle", "age": 34],
["name": "Jenny", "age": 18],
]

还有一个像这样的字符串数组:

["Kyle, Jack"]

我希望使用字符串数组来过滤字典数组,因此它最终像这样:

[
["name": "Kyle", "age": 34],
["name": "Jack", "age": 20],
]

这是因为我希望我的 Collection View 仅显示第一个数组中的项目,如果它们的名称在第二个数组(只有字符串的那个)中。还有其他 Collection View ,每个 View 都将使用不同的字符串数组进行过滤。

我该怎么做?

我试过做类似的事情:

if nameArray[indexPath.item] == dictionaryArray[indexPath.item]["name"] {
//code for cell here
}

但它不显示字符串数组中的单元格顺序。它会做类似的事情:

[empty cell] [Jack's cell]

谢谢!

最佳答案

您可以使用 map :

arrStrings.map { str in
return arrDicts[arrDicts.index(where: { dict in
if let name = dict["name"] as? String {
return name == str
}
return false
})!]
}

效率不是很高,但是因为要保持顺序,所以我觉得在字典数组中查找还是很有必要的。

这假定存在名称由字符串数组指定的字典。如果它们可能存在或可能不存在,您可以尝试:

arrStrings.compactMap { str -> [String: Any]? in
guard let index = arrDicts.index(where: { dict in
if let name = dict["name"] as? String {
return name == str
}
return false
}) else { return nil }
return arrDicts[index]
}

关于swift - 从字符串数组中获取新的字典数组,以在 Collection View 中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462888/

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