【问题标题】:Cannot access value through keys in nsdictionary无法通过 nsdictionary 中的键访问值
【发布时间】:2016-03-11 21:10:57
【问题描述】:

我很困惑这是什么问题,我的字典是:

eventDetails = (WebHandler.sharedInstance.eventsDictionary?.copy())! as! NSDictionary


print("Printing eventdeatails: '\(eventDetails)'")

Printing event details: '{
    0 =     {
        "_id" = 5661958b2c0fee491a9e9e08;
        date = "9am - 1pm";
        degree = ee;
        eventCategory = sports;
        eventDescription = "cricket match between east and west wing";
        eventPhoto = "";
        eventTitle = "cricket match";
        location = "west wing hall";
        society = "the society that has nothing better to do";
        universityId = ucf;
    };
    3 =     {
        "_id" = 5661981b69439a6a1b17870e;
        date = "8am - 3pm";
        degree = ee;
        eventCategory = sports;
        eventDescription = "football match between batch 13 and 14";
        eventPhoto = "";
        eventTitle = "football match";
        location = "west wing hall";
        society = "King KOng";
        universityId = ucf;
    };
    1 =     {
        "_id" = 566195a72c0fee491a9e9e09;
        date = "8am - 3pm";
        degree = ee;
        eventCategory = sports;
        eventDescription = "football match between batch 13 and 14";
        eventPhoto = "";
        eventTitle = "football match";
        location = "west wing hall";
        society = "King KOng";
        universityId = ucf;
    };
    2 =     {
        "_id" = 566195b12c0fee491a9e9e0a;
        date = "8am - 3pm";
        degree = ee;
        eventCategory = entertainment;
        eventDescription = "showing the harry potter!";
        eventPhoto = "";
        eventTitle = "movie showing";
        location = "west wing hall";
        society = "the society that has nothing better to do";
        universityId = ucf;
    };
}'

这就是我从我的网络处理程序类中获取它的方式。我设置了非常简单的键 0, 1 , 2, ... 只是为了在需要时轻松获取。 它正在正确打印完整的字典,但是每当我尝试访问该值时,它都会让我获得那些特定的值,而不是我得到'nil' 结构是我有 dict 和 dict 我现在尝试过的是

let key = "2"
print(eventDetails[key]!) //not working

print(eventDetails["2"]!) // just for confirmation, not working

print(eventDetails["2"]!["_id"]!) // not working
print(eventDetails.valueForKey(idnumber)) // i have doubt on word "key" so i changed it and observed it but not good for me

请帮我推荐一些好的读物或一些我可以找到基础知识或给我一些出路的东西。我现在一无所知。 提前致谢!

【问题讨论】:

  • 你试过print(eventDetails[2]!)吗?
  • @setonugroho 指出“2”与 2 不同。
  • 你能记录 eventDetails 中的所有键和值吗?
  • 非常感谢,其实我有想过 key 是 String 的类型,我什至没有想到。

标签: ios swift dictionary key-value


【解决方案1】:

您的字典以整数值作为键,因此您必须使用 NSInteger(或 Int)类型的键来访问字典。试试:

let key = 2
print(eventDetails[key]!)
print(eventDetails[2]!)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 2012-06-25
    • 2020-06-26
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多