繁体   English   中英

Swift:在嵌套字典中发布访问密钥

[英]Swift: Issue accessing key in nested dictionary

我在访问嵌套字典中的键时遇到问题。

在我的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是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(“ Current dot is”)输出:

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

建议在currentDots [403986692]上进行查找的..只会返回字典,而不会。 当我遍历temp对象时,在Xcode中显示为正在键入:

([String:protocol <>?])

有人知道我在做什么错吗? 您的帮助将不胜感激。

谢谢!

尝试更改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 )")
           }
       }
    }
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM