Mahi008 Mahi008 - 1 year ago 170
Swift Question

Swift - How to loop through NSDictionary

Hi I'm currently learning Swift, and I wanted to extract data from a JSON Api, My Swift code looks like this. To be specific, I need to extract each and every key and its value,(for example: print the value of title, cover etc..)

//Json request
var error: NSError?
var raw = NSString.stringWithString("")
var api_url = NSURL.URLWithString(raw)
let jsonData: NSData = NSData.dataWithContentsOfURL(api_url, options: nil, error: &error)
let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)
as NSDictionary
for val in result {
for (var i=0; i < val.value.count; i++){
//println(val.value.valueAtIndex(3)) Not Working

and the structure of my JSON is

data: [
id: 2,
title: "Hunger Games",
cover: "",
genre: 2


Answer Source

Here is how you can process a given JSON:

let dataArray = result["data"] as NSArray;

print("Data items count: \(dataArray.count)")

for item in dataArray { // loop through data items
    let obj = item as NSDictionary
    for (key, value) in obj {
        print("Property: \"\(key as String)\"")


Remember that you receive parsed objects as NSDictionary and when you iterate through the dictionary, order in which you receive properties may differ from the order in the original JSON.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download