2016-12-07 76 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];這將是很好:) –