2016-12-07 79 views
-2
let json: [AnyObject] = { 
      "response": "get_nearby_deals", 
      "userID": "12345", 
      "demo":[{"deal_code":"iD1612061"}] 
      } 

如何在Swift中声明字典?我是Swift新手。完全卡住了。swift中的字典

+2

基本上:'[]'包含**一个**类型总是一个数组,包含**两个**类型冒号分隔的是一个字典。 – vadian

回答

4

您已经使用[AnyObject]宣布Array,只是将其更改为[String: Any],并用方括号[]替换大括号{}

let json: [String: Any] = [ 
          "response": "get_nearby_deals", 
          "userID": "12345", 
          "demo":[["deal_code":"iD1612061"]] 
          ] 

而且你可以检索使用subscript这样Dictionary值。

let userID = json["userID"] as! String 
//Above will crash if `userID` key is not exist or value is not string, so you can use optional wrapping with it too. 
if let userID = json["userID"] as? String { 
    print(userID) 
} 

//`demo` value is an array of [String:String] dictionary(s) 
let demo = json["demo"] as! [[String:String]] 
//Same here as the previous `userID`, it will crash if 'demo' key is not exist, so batter if you optionally wrapped it: 
if let demo = json["demo"] as? [[String:String]] { 
    print(demo) 
} 
+0

回复内容不存在{} –

+0

@ThripthiHaridas你有没有尝试过像我的回答。 –

+0

我投了票,但我建议添加一些代码来展示如何从中获取值,因为它是[String:Any];这将是很好:) –