在Swift 3中获取多级字典信息的最佳方法是什么

时间:2016-12-27 23:09:28

标签: ios swift xcode

我有格式词典

myDict: Dictionary <String, Dictionary>

例如,

“AUTOID-1” {
    “key1” : “val1_1”,
    “key2” : “val2_1:
},
“AUTOID-2” {
    “key1” : “val1_2”,
    “key2” : “val2_2:
},
“AUTOID-3” {
    “key1” : “val1_3”,
    “key2” : “val2_3:
}

对于整个数据集,我想找出最高最高 key2 AUTOID 的值强>

使用

myKeyData = myDict.allKeys

我可以获得所有 AUTOID 的数组,然后我可以使用以下内容进行进一步处理:

for index in 0...myKeyData.count-1 {

    if let insideDict = myDict[myKeyData[index]] as? NSDictionary {
        // FURTHER PROCESSING  
    } 
}

是否有更好的方法来实现找到与 key2 最高最低值相对应的 AUTOID 的目标

2 个答案:

答案 0 :(得分:1)

我会使用map来获取包含键("AUTOID-N")和值("valX_Y")的元组数组,然后获取min和{{1}根据仅比较值的比较器来计算该数组。

max

答案 1 :(得分:0)

使用reduce

let myDict = ["AUTOID-1": ["key1" : "val1_1", "key2" : "val2_1"],
              "AUTOID-2": ["key1" : "val1_2", "key2" : "val2_2"],
              "AUTOID-3": ["key1" : "val1_3", "key2" : "val2_3"]]

let initalElement = (min: myDict.first!, max: myDict.first!)
let result = myDict.reduce(initalElement) { (aggregate, element) in
    guard let minValue = aggregate.min.value["key2"],
        let maxValue = aggregate.max.value["key2"],
        let currentValue = element.value["key2"] else {
            return aggregate
    }

    let newMin = currentValue < minValue ? element : aggregate.min
    let newMax = currentValue > maxValue ? element : aggregate.max
    return (min: newMin, max: newMax)
}

print(result.min)
print(result.max)

这假设myDict非空。您基本上选择myDict的第一个元素来启动reduce循环,并将其与myDict中其余的键值对进行比较。