Accessing Nested NSDictionary values in Swift 3.0

你说的曾经没有我的故事 提交于 2019-12-11 07:32:49

问题


I have the following data I received from Firebase. I have made my snapshotValue a NSDictionary.

self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in
            let snapshotValue = snapshot.value as? NSDictionary
            print(snapshotValue, "snapshotValue")
            //this line of code doesn't work
            //self.pictureURL = snapshot["picture"]["data"]["url"]
        }) { (error) in
            print(error.localizedDescription)
        }

I tried How do I manipulate nested dictionaries in Swift, e.g. JSON data? , How to access deeply nested dictionaries in Swift , and other solutions yet no luck.

How do I access the url value inside the data key AND the picture key?

I can make another reference in Firebase and get the value, but I'm trying to save another request. 😓


回答1:


When you refrence to a key of a Dictionary in swift you get out an unwrapped value. This means it can be nil. You can force unwrap the value or you can use pretty if let =

this should probably work.

if let pictureUrl = snapshot["picture"]["data"]["url"] {
    self.pictureURL = pictureUrl
}



回答2:


Try using :-

 if let pictureDict = snapshot.value["picture"] as? [String:AnyObject]{

        if let dataDict = pictureDict.value["data"] as? [String:AnyObject]{

              self.pictureURL =  dataDict.value["url"] as! String

           }
   }



回答3:


Inline dictionary unwrapping:

let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String



回答4:


You can use the following syntax, that is prettier:

    if let pictureDict = snapshot.value["picture"] as? [String:AnyObject],
        let dataDict = pictureDict.value["data"] as? [String:AnyObject] {
            self.pictureURL =  dataDict.value["url"] as! String
        }
    }


来源:https://stackoverflow.com/questions/40120042/accessing-nested-nsdictionary-values-in-swift-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!