如何循环浏览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?

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

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

更多swifty

let groups = [["groupName" : "a"], ["groupName" : "b"]]
let groupNames = groups.map { (elem) -> String in
    return elem["groupName"]!
}
print(groupNames) //returns ["a", "b"]

最新更新