【问题标题】:Swift: Issue accessing key in nested dictionarySwift:问题访问嵌套字典中的键
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多