Swift中的字典数组

时间:2014-07-02 21:58:10

标签: arrays json dictionary swift

似乎无法找到正确的语法。试图从json文件中获取一系列dicts:

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"
    }
    ]
}

2 个答案:

答案 0 :(得分:6)

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

您可能正在寻找的是:

let books = jsonDict["books"]

编译器应该能够推断出那里有什么。如果没有,您可以使用:

进行投射
let books = jsonDict["books"] as Array<Dictionary<String, String>>

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

答案 1 :(得分:0)

在Swift 2中,类型转换如下工作!

[[String: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
},
+{ ... },
+{ ... },
+{ ... },
+{ ... },
+{ ... }
]
}

快速代码推导如下

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