Chris Mikkelsen Chris Mikkelsen - 5 days ago 4
Swift Question

How to loop through NSDictionary to get specific values

I have an NSDictionary that looks like this.

{
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.";
}


I'd like to get all groupName values, let's just say just I'd like to print them in the console for now.

How do I iterate through this NSDictionary?

asdasdasd

Answer

Assuming dictionary is the root object this code prints all groupName strings

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