【问题标题】:Dictionary in swift快速字典
【发布时间】:2016-12-07 10:12:05
【问题描述】:
let json: [AnyObject] = {
            "response": "get_nearby_deals",
            "userID": "12345", 
            "demo":[{"deal_code":"iD1612061"}]
            }

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

【问题讨论】:

  • 基本上:[] 包含 一个 类型始终是一个数组,包含 两个 类型的冒号分隔是一个字典。

标签: swift dictionary swift2


【解决方案1】:

您已使用[AnyObject] 声明Array,只需将其更改为[String: Any] 并将大括号{} 替换为方括号[]

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

您可以像这样使用subscriptDictionary 检索值。

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];那会很好:)
  • @ThripthiHaridas 服务器发送 JSON。 JSON 字典/数组的语法与 Swift 字典/数组不同。 JSON 数组:[],JSON 字典:{:},Swift 数组:[],Swift 字典:[:]
  • @ThripthiHaridas Nirav 是对的。您不直接声明 JSON 语法。您需要一个 Swift 字典,然后将其转换为 JSON。或者你拿一个转换成 Swift 的 JSON 字典。如果您仍然不确定,请探索my JSON answers,这里有很多例子——我不想再写同样的东西了。 ;)
猜你喜欢
  • 2014-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
相关资源
最近更新 更多