let json: [AnyObject] = {
"response": "get_nearby_deals",
"userID": "12345",
"demo":[{"deal_code":"iD1612061"}]
}
如何在Swift中聲明字典?我是Swift新手。完全卡住了。swift中的字典
let json: [AnyObject] = {
"response": "get_nearby_deals",
"userID": "12345",
"demo":[{"deal_code":"iD1612061"}]
}
如何在Swift中聲明字典?我是Swift新手。完全卡住了。swift中的字典
您已經使用[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)
}
回覆內容不存在{} –
@ThripthiHaridas你有沒有嘗試過像我的回答。 –
我投了票,但我建議添加一些代碼來展示如何從中獲取值,因爲它是[String:Any];這將是很好:) –
基本上:'[]'包含**一個**類型總是一個數組,包含**兩個**類型冒號分隔的是一個字典。 – vadian