简体   繁体   中英

Swift: Issue accessing key in nested dictionary

I am having trouble accessing keys within a nested dictionary.

In my ViewDidLoad I have defined the dictionary (currentDots) to store String keys and any object as the value:

ViewDidLoad

var currentDots = Dictionary<String, Any>()

Here it is listening for objects on a callback and writing dictionaries to the currentDots dictionary..no problem, works fine:

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

However here, I'm unable to parse the keys inside the Dictionary and despite the above statement writing dictionaries as a Dictionary object, the compiler skips past the if temp is Dictionary statement:

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

The output I get for println("Current dot is") just before the "if" statement:

403986692: [range: Optional(500), description: Optional(This is a test dot!), name: Optional(mudchute DLR), location: Optional(<+51.49173972,-0.01396433> +/- 0.00m (speed -1.00 mps / course -1.00) @ 17/12/2014 15:12:09 Greenwich Mean Time)],

..which suggests a lookup on currentDots[403986692] should just return a dictionary and it does not. When I trace through the temp object shows in Xcode as being type:

([String : protocol<>?])

Does anyone have any idea what I am doing wrong here? Your help would be much appreciated.

Thanks!

Try changing the declaration of currentDots , as I think parts of the issue are related to you making an Any optional, and that isn't really a good idea:

var currentDots = Dictionary<String, AnyObject>()

And then try the following for 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 )")
           }
       }
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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