【问题标题】:Array of dictionaries in SwiftSwift 中的字典数组
【发布时间】:2014-08-23 20:53:30
【问题描述】:

似乎找不到正确的语法。尝试从 json 文件中获取字典数组:

let books:Array = jsonDict["books"] as Array
//Cannot convert the expression's type Array<$T4> to type StringLiteralConvertible

let books:Array = jsonDict["books"] as Array<Dictionary>
//Reference to generic type "Dicionary" requires arguments in <...>

json 看起来像这样:

{
  "id": "1",
  "title": "title one",
  "books": [
    {
      "id": "1",
      "title": "book title one"
    },
    {
      "id": "2",
      "title": "book title two"
    }
    ]
}

【问题讨论】:

  • Array&lt;Dictionary&lt;String, String&gt;&gt;?
  • 哇,太丑了。不过还好……

标签: arrays json dictionary swift


【解决方案1】:

当您指定一个数组时,您还必须具体并列出数组中的内容。你还需要

您可能正在寻找的是:

let books = jsonDict["books"]

编译器应该能够推断出其中的内容。如果没有,您可以使用:

let books = jsonDict["books"] as Array<Dictionary<String, String>>

不需要类型转换书籍的类型说明符。

【讨论】:

  • 我当然更喜欢第一个,而且它似乎有效。但是我收到一个警告:推断常量“books”的类型为“AnyObject”,这可能是意外的。
  • 对,那样的话,肯定用第二个。这可能是因为 jsonDict 的类型为 Dictionary&lt;String, AnyObject&gt; 或类似的类型,会给你一个 AnyObject
  • 它也适用于 Swift 2 吗? (我收到错误'String?' is not convertible to 'Array&lt;Dictionary&lt;String, String&gt;&gt;')
【解决方案2】:

在 Swift 2 中,可以进行如下类型转换!

[[字符串:AnyObject]]

我用例子测试过

-{
"city" : +{ ... },
"cod" : 200,
"message" : 0.0068,
"cnt" : 6,
"list" : -[
-{
"dt" : 1461369600,
"main" : +{ ... },
"weather" : +[ ... ],
"clouds" : +{ ... },
"wind" : +{ ... },
"rain" : +{ ... },
"sys" : +{ ... },
"dt_txt" : 2016-04-23 00:00:00
},
+{ ... },
+{ ... },
+{ ... },
+{ ... },
+{ ... }
]
}

swift代码推导如下

let theJSONData = try NSJSONSerialization.JSONObjectWithData(theData!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]

let theList = theJSONData["list"] as! [[String: AnyObject]] // Array of Dictionaries
let dayOneWeather = theList[0]
let mainDayOneWeather = dayOneWeather["main"] as! [String:AnyObject]
let dayOneTemperature = mainDayOneWeather["temp"] as! Int
let dayOneTemperatureInDegreeCelsius = dayOneTemperature - 273

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    相关资源
    最近更新 更多