ios - 在swift中遍历nsdictionary

标签 ios swift nsdictionary

我是 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'

最佳答案

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

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

在闭包中,$0.1 表示当前字典的($0.0 将是)。结果是一个日期字符串数组。

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)
}

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

但是,如果只有一个 Gold 条目,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)。

关于ios - 在swift中遍历nsdictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985489/

相关文章:

ios - 从 firebase 检索信息

ios - 如何使用 Moya 取消多个网络请求

iOS 属性文本删除/n 换行符

ios - 正确检测键盘的出现和消失

swift - 尝试在 iOS (swift) 中使用 Facebook Graph API 获取 'age_range' 但缺少 'max' 值?

ios - (iOS) 从 Documents 文件夹中读取 plist - 我得到正确的路径但无法加载字典

ios - 如何使用 Swift 3 在 Apple map 中将 GeoJSON 绘制为叠加层

iphone - 在 TableView 中解析字典的 JSON 数组

objective-c - 从 JSON 数组 objective-c 获取值时出现问题

swift - CFError 到 NSError 的免费桥接在 Swift 3 中不起作用