我是新手。 我的字典是
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 = "";
};
}
我想获取reward
是Gold
的所有日期
有人可以帮我吗?
我现在尝试的是:
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'
答案 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 的答案,以获取深入的解释和实现该目的的快速方法。
谢谢