【发布时间】:2020-03-08 19:13:14
【问题描述】:
我正在尝试解析以下 json 并希望检索其值与给定值匹配的字典的“键”。
{ "OuterArrayHolder" :
[
{
"dictDynamicKey" : ["dynamicValue1", "dynamicValue2", "dynamicValue3"]
},
{
"dictAnotherDynamicKey" : ["dynamicValue4", "dynamicValue5", "dynamicValue6"]
},
]
}
[注意:在上面的json中,所有的键和值都是动态的,除了“OuterArrayHolder”。]
我已经以非 Swifty 的方式实现了它,目前 获得了预期的输出,但我不知道如何使用 swift 的高阶函数来完成相同的行为.
输入:“dynamicValue2”
预期输出:“dictDynamicKey”
目前的解决方案:
let inputValue = "dynamicValue2"
if !outerArrayHolder.isEmpty {
for dynamicDict in outerArrayHolder {
for (key, value) in dynamicDict {
if value.empty || !value.contains(inputValue) {
continue
} else {
//here if inputValue matches in contianed array (value is array in dictionary) then I want to use its "repective key" for further businisess logic.
}
}
}
}
我想减少这两个 for 循环,并希望使用高阶函数来实现确切的行为,非常感谢这方面的任何帮助。
【问题讨论】:
-
for...in的高阶函数版本是forEach。除此之外,很难看出您还有什么期望。我不确定我是否明白您对此的看法是“非 Swifty”。您正在做一些不必要的事情;例如,if !outerArrayHolder.isEmpty毫无意义,因为如果它为为空,则for...in循环无论如何都不会执行。说if condition...continue...else...otherthing是愚蠢的,因为你还不如说if !condition otherthing。但这与“高阶”无关;只是你过于冗长了。 -
@matt 除了不必要的东西,您能否建议是否有任何其他方法可以使用高阶函数检索 dynamicKey 并避免 for-in/forEach。
-
forEach是一个高阶函数。不清楚您想象的“高阶函数”会为您做什么或将为您做什么,这与您正在做的事情不同。循环就是循环,不管如何表达。 -
你这样做了多少次?因为对字典数组进行线性搜索,对每个条目进行线性搜索,对每个值数组进行线性搜索对于大型数据集或频繁访问来说真的很慢。
-
@matt 我的意思是使用“过滤器”功能。像 outerArrayHolder.filter {($0...一些代码在这里.......)}
标签: ios swift for-loop swift4 higher-order-functions