遍历 swift 中的 nsdictionary

Traverse nsdictionary in swift

我是 swift 的新手。 我的字典是

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'

从第一个 for in 循环开始,您将在临时变量中获取 NSDictionary

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

所以,你应该直接在 temp 上检查 .value(forKey:) 并获得 reward 的值。

你应该这样试试

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 的答案以获得深入的解释和实现相同目的的纯 swift 方法。

谢谢

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

(强烈)推荐的 Swift 方法是使用 filter 函数。这比循环更有效。

在闭包中 [=15=].1 表示当前字典的 value[=17=].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 { [=10=].1["reward"] as? String == "Gold" }
    let allDates = Array(goldData.keys)
    print(allDates)
}

代码安全地解包了所有可选值。

然而,如果只有 一个 黄金条目,first 函数仍然比 filter

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

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