我有一段从API获取信息的代码,我需要将它添加到Dictionary中。代码如下:
typealias JSONdic = [String: AnyObject]
var weatherData: AnyObject = StorageManager.getValue(StorageManager.StorageKeys.WeatherData)!
let json: AnyObject = ["Any": "Object"]
if let json = json as? JSONdic, history = json["history"] as? JSONdic, tempi = history["tempi"] as? Int, hum = history["hum"] as? String, precip = history["precipi"] as? String{
println("Temperature:\(tempi) Humidity:\(hum) Precipitation:\(precip)")
weatherData = [NSDate: AnyObject]()
let temp = tempi as NSNumber
weatherData[(The Current Date)] = temp
}
我想首先将“temp”添加到weatherData Dictionary,但即使将其转换为NSNumber,我也被告知NSNumber值无法分配给AnyObject?!类型。任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
您的weatherData
变量属于AnyObject
类型。尽管您稍后为其分配了[NSDate: AnyObject]
类型的值,但编译器仍将变量本身视为AnyObject
。然后您遇到问题,因为您尝试下标,分配NSNumber
,这显然不可能在AnyObject
上。
您对weatherData
的声明应该确保它是您想要的类型。如果您确定StorageManager
将为您返回天气数据键的相应字典类型,则可以强制将其向下转换为正确的类型:
var weatherData = StorageManager.getValue(StorageManager.StorageKeys.WeatherData) as! [NSDate: NSObject]