获取选定元素的键和索引Swift [英] Get key and indices of selected elements Swift
问题描述
我有一本字典,其中包含一组字典.
I have one dictionary that contains an Array of Dictionaries.
"other":(
{
"grocery_section" = other,
name = test
},
{
"grocery_section" = other,
name = test1
},
{
"grocery_section" = other,
name = test2
}
),
"c0f5d6c5-4366-d310c0c9942c": (
{
"grocery_section" = refrigerated,
name = "Nondairy milk"
},
{
"grocery_section" = other,
name = "test
}
)
现在,我想要的是键和索引,其中name = test .现在,我正在迭代字典并在其中获取
Now, What I want is the key and index where name = test. Right now I am iterating dictionary and inside that get the indexes of elements like
for (key, value) in list {
print(key)
print((value as! [String:String]).indices.filter { (value as! [String:String])[$0]["name"] == "test"})
}
它有效,但我认为它不是有效的方法.因此,需要一种更有效的方法.
主要问题是如何用另一个元素替换或更新该元素.例如,我要在name = test
的两个元素中都添加status = "true"
.我也可以通过循环运行或查找元素并将其替换来做到这一点.但是我需要一些有效的方法.
It works but I don't think its efficient way. So, Need a more efficient way.
And the main question is how to replace or update the element with another element. For example, I want to add status = "true"
in both the elements where name = test
. That too I can do by looping things or finding elements and replace it. But I need some efficient way to do so.
推荐答案
您可以使用flatMap
和compactMap
:
let matches = list.flatMap { key, value in
// go through all elements in the array and convert the matching dictionaries in (key, index) pairs
value.enumerated().compactMap { index, dict in
dict["name"] == "test" ? (key, index) : nil
}
}
print(matches)
示例输出:
[("other", 0), ("c0f5d6c5-4366-d310c0c9942c", 1)]
如果要避免同一密钥重复配对,可以使用map
代替compactMap
:
If you want to avoid repeated pairs for the same key, you can use map
instead of compactMap
:
let matches = list.map { key, value in
(key, value.enumerated().compactMap { index, dict in
dict["name"] == "test" ? index : nil
})
}
示例输出:
[("other", [0]), ("c0f5d6c5-4366-d310c0c9942c", [1])]
内部compactMap
将仅在名称匹配的项目上构建一个数组,而外部flatMap
将使原本为二维的数组变平.
The inner compactMap
will build an array made of on only the items that have the name matching, while the outer flatMap
will flatten an otherwise bi-dimensional array.
这篇关于获取选定元素的键和索引Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!