首页 文章

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

提问于
浏览
2

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

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

ViewDidLoad

var currentDots = Dictionary<String, Any>()

这里它正在侦听回调中的对象并将字典写入currentDots字典..没问题,工作正常:

Query Handler

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语句:

Annotate Dot

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),位置:可选(<51.49173972,-0.01396433> / - 0.00m(速度-1.00 mps /当然-1.00)@ 17/12/2014 15:12:09格林威治标准时间)],

..which建议查找currentDots [403986692]应该只返回一个字典而不是 . 当我通过临时对象跟踪时,在Xcode中显示为类型:

([String:protocol <>?])

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

谢谢!

1 回答

  • 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 )")
               }
           }
        }
     }
    

相关问题