Swift:在嵌套字典中发出访问密钥的问题

时间:2014-12-17 15:36:33

标签: ios swift dictionary xcode6

我在嵌套字典中访问密钥时遇到问题。

在我的ViewDidLoad中,我已经定义了字典(currentDots)来存储String键和任何对象作为值:

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是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)
        }
    }
}

我在“if”语句之前获得println的输出(“当前点是”):

403986692:[范围:可选(500),描述:可选(这是一个测试点!),名称:可选(mudchute DLR),位置:可选(&lt; + 51.49173972,-0.01396433&gt; +/- 0.00 m(速度-1.00 mps / course -1.00)@ 17/12/2014 15:12:09 Greenwich Mean Time)],

..这表明在currentDots上查找[403986692]应该只返回一个字典而不是。当我在Xcode中显示临时对象时显示为类型:

([String:protocol&lt;&gt;?])

有谁知道我在这里做错了什么?非常感谢您的帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试更改currentDots的声明,因为我认为部分问题与您Any选项有关,这不是一个好主意:

var currentDots = Dictionary<String, AnyObject>()

然后针对annotateDot(key: String)尝试以下内容:

func annotateDot(key: String) {
    if let dot = currentDots[key] as? Dictionary<String, AnyObject> {

       // This for the name ...
       if let name = dot["name"] as? String {
          println("=== \(name) ===")
       }

       // ... or this to print all keys           
       for (key, value) in dot {
           if key != "name" {
               println ("\(key) : \( value )")
           }
       }
    }
 }