快速遍历nsdictionary

时间:2018-08-23 12:08:22

标签: ios swift nsdictionary

我是新手。 我的字典是

monthData = 
{
    "2018-08-10" = {
        accuracy = 71;
        attempted = 7;
        correct = 5;
        reward = Bronze;
    };
    "2018-08-12" = {
        accuracy = 13;
        attempted = 15;
        correct = 2;
        reward = "";
    };
    "2018-08-13" = {
        accuracy = 33;
        attempted = 15;
        correct = 5;
        reward = "";
    };
    "2018-08-14" = {
        accuracy = 100;
        attempted = 15;
        correct = 15;
        reward = Gold;
    };
    "2018-08-16" = {
        accuracy = 73;
        attempted = 15;
        correct = 11;
        reward = Silver;
    };
    "2018-08-21" = {
        accuracy = 26;
        attempted = 15;
        correct = 4;
        reward = "";
    };
    "2018-08-23" = {
        accuracy = 46;
        attempted = 15;
        correct = 7;
        reward = "";
    };
}

我想获取rewardGold的所有日期

有人可以帮我吗?

我现在尝试的是:

for (key,value) in monthData{
   let temp = monthData.value(forKey: key as! String) as! NSDictionary
   for (key1,value1) in temp{
     if((value1 as! String) == "Gold"){
       print("keyFINAL \(key)")
     }
}

但输出错误Could not cast value of type '__NSCFNumber' to 'NSString'

2 个答案:

答案 0 :(得分:1)

发生错误是因为迭代字典时,您将Int值强制转换为String是不可能的

(高度)推荐的Swift方法是使用filter函数。这比循环要有效得多。

在闭包中,$0.1代表当前字典的value$0.0将是key)。结果是日期字符串数组。

let data : [String:Any] = ["monthData" : ["2018-08-10": ["accuracy" : 71, "attempted" ... ]]]

if let monthData = data["monthData"] as? [String:[String:Any]] {
    let goldData = monthData.filter { $0.1["reward"] as? String == "Gold" }
    let allDates = Array(goldData.keys)
    print(allDates)
}

代码可以安全地包装所有可选内容。

但是,如果只有 1个金牌,则first功能仍然比filter

更有效
if let monthData = data["monthData"] as? [String:[String : Any]] {
    if let goldData = monthData.first( where: {$0.1["reward"] as? String == "Gold" }) {
       let goldDate = goldData.key
        print(goldDate)
    }
}

在Swift中,尽可能避免使用ObjC运行时(value(forKey:))和Foundation集合类型(NSDictionary)。

答案 1 :(得分:0)

从第一个for循环中,您将获得NSDictionary的临时变量

"2018-08-16" =     {
    accuracy = 73;
    attempted = 15;
    correct = 11;
    reward = Silver;
};

因此,您应该直接检查temp上的.value(forKey :)并获取奖励值。

您应该这样尝试

for (key,value) in monthData {
        let temp = monthData.value(forKey: key as! String) as! NSDictionary
        if(((temp.value(forKey: "reward")) as! String) == "Gold"){
            print("keyFINAL \(key)")
        }
    }

尝试并分享结果

编辑

请查看 vadian 的答案,以获取深入的解释和实现该目的的快速方法。

谢谢