2016-12-01 37 views
-3

我有一个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."; 
} 

我想获得的所有组名的价值观,让我们只说只是我想将它们打印在控制台现在。

如何遍历此NSDictionary?

回答

2

假设dictionary是根对象的代码打印所有groupName

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

此代码的工作! –

1

更多SWIFTY

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

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

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