如何循环遍历NSDictionary以获取特定值

时间:2016-12-01 05:38:32

标签: swift nsdictionary

我有一个看起来像这样的NSDictionary。

{
groups =     (
            {
        color = "<null>";
        createdBy = System;
        groupName = "Best friends";
        groupType = regular;
        id = 583562ede4b030a2a979dfa3;
        lastModifiedOn = "<null>";
        maxNoOfMembersAllowed = 9;
        members = "<null>";
        pictureLastModifiedOn = "<null>";
        position = 1;
        searchCriteria = "<null>";
        status = Active;
    },
            {
        color = "<null>";
        createdBy = System;
        groupName = Family;
        groupType = regular;
        id = 583562ede4b030a2a979dfa6;
        lastModifiedOn = "<null>";
        maxNoOfMembersAllowed = 9;
        members = "<null>";
        pictureLastModifiedOn = "<null>";
        position = 2;
        searchCriteria = "<null>";
        status = Active;
    },
            {
        color = "<null>";
        createdBy = System;
        groupName = Work;
        groupType = regular;
        id = 583562ede4b030a2a979dfa9;
        lastModifiedOn = "<null>";
        maxNoOfMembersAllowed = 9;
        members = "<null>";
        pictureLastModifiedOn = "<null>";
        position = 3;
        searchCriteria = "<null>";
        status = Active;
    }
);
status = Success;
statusText = "Group:Get Successful."; 
}

我想获取所有groupName值,我们只想说我现在想在控制台中打印它们。

如何遍历此NSDictionary?

2 个答案:

答案 0 :(得分:2)

假设dictionary是根对象,此代码将打印所有groupName字符串

if let groups = dictionary["groups"] as? [[String:Any]] {
    for group in groups {
       print(group["groupName"] as! String)
    }
}

答案 1 :(得分:1)

更多Swifty

let groups = [["groupName" : "a"], ["groupName" : "b"]]

let groupNames = groups.map { (elem) -> String in
    return elem["groupName"]!
}

print(groupNames) //returns ["a", "b"]