【发布时间】:2014-12-17 15:36:33
【问题描述】:
我在访问嵌套字典中的键时遇到问题。
在我的 ViewDidLoad 中,我定义了字典 (currentDots) 来存储字符串键和任何对象作为值:
ViewDidLoad
var currentDots = Dictionary<String, Any>()
这里它在回调中监听对象并将字典写入 currentDots 字典..没问题,工作正常:
查询处理程序
func setupQueryHandle(query: GFCircleQuery) {
var queryHandle = query.observeEventType(GFEventTypeKeyEntered, withBlock: { (key: String!, location: CLLocation!) in
var dotRef = firebaseReference.childByAppendingPath("dotLocation/\(key)")
dotRef.observeEventType(.Value, withBlock: { snapshot in
self.currentDots[key] = ["name": snapshot.value.objectForKey("dot_name") , "description": snapshot.value.objectForKey("dot_description"), "range": snapshot.value.objectForKey("range"), "location": location ]**
self.annotateDot(key)
}, withCancelBlock: { error in
println(error.description)
})
})
}
但是在这里,我无法解析 Dictionary 中的键,尽管上述语句将字典编写为 Dictionary 对象,但编译器跳过了 if temp is Dictionary 语句:
注释点
func annotateDot(key: String) {
if currentDots[key] as Any? != nil {
let temp = currentDots[key]!
println("Current dot is... \(temp)")
if temp is Dictionary<String,Any> {
println(currentDots[key]!)
let dotDictionary = currentDots[key] as Dictionary <String, AnyObject>
let dotName = dotDictionary["name"] as String
println(dotName)
}
}
}
println("Current dot is") 在 "if" 语句之前得到的输出:
403986692:[范围:可选(500),描述:可选(这是一个测试点!),名称:可选(泥路 DLR),位置:可选( +/- 0.00m(速度 -1.00 mps / 课程 -1.00) @ 2014 年 12 月 17 日 15:12:09 格林威治标准时间)],
..这表明在 currentDots[403986692] 上的查找应该只返回一个字典,但它没有。当我在 Xcode 中跟踪临时对象时显示为类型:
([String : 协议?])
有人知道我在这里做错了什么吗?非常感谢您的帮助。
谢谢!
【问题讨论】:
-
只是一个注释:使用
if let temp = currentDots[key] { ...而不是两行。这将自动测试。temp无论如何都会是Any,因为currentDots是这样声明的。
标签: ios swift dictionary xcode6