Search code examples
iosjsonswifttwitter

Get string inside NSDictionary in swift


I have made a struct that is helping me fetching info from a twitter json. The json has values such as text, which I am able to fetch without a problem, but it also has a dictionary names user and it has the string screen_name inside it.

How can I access that string?

Here is how I access the text string and how I fetch the user dictionary:

func parseTwitterJSON(_ data:Data) {

    var jsonResult = NSArray()

    do{
        jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray

    } catch let error as NSError {
        print(error)
    }

    var jsonElement = NSDictionary()
    let twitterLocations = NSMutableArray()

    for i in 0 ..< jsonResult.count{
        jsonElement = jsonResult[i] as! NSDictionary
        let twitterLocation = twitterLocationModel()
        //the following insures none of the JsonElement values are nil through optional binding
        if let lang = jsonElement["lang"] as? String,
            let text = jsonElement["text"] as? String,
            let user = jsonElement["user"] as? NSDictionary
        {

            twitterLocation.lang = lang
            twitterLocation.text = text
            twitterLocation.user = user    
        }

        twitterLocations.add(twitterLocation)   
    }

    DispatchQueue.main.async(execute: { () -> Void in
        self.delegate.twitterDownloaded(items: twitterLocations)
    })
}

Solution

  • To access the value of a key from a dictionary you would use

    let myDictName : [String:String] = ["keyName" : "value"]
    let value = myDictName["keyName"]
    //value will be equal to "value"
    

    Since you have the element user as an dictionary, you can just say

    let userName = user["screen_name"]