2016-12-01 38 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"]