kumar kumar - 7 months ago 30
Swift Question

How to fetch the key from JSON in Swift?

I am working on JSON parsing in Swift.

var results = [String:[AnyObject]]()


The above
results
is having the data as shown below,


"fruit" = (
"apple",
"orange"
);


Here, data is appended dynamically during runtime. All I need is to get the keys and display them in table view as header.

How to get the
key
from
results
in swift?

Answer

I have used,

var results = [String:Array<DataModel>]()

where,

class DataModel {
    var name: String?     
}

and to fetch the keys and value,

for i in 0...(results.length-1){
    // To print the results keys
    print(results.keys[results.startIndex.advancedBy(i)])
    // To get value from that key
    let valueFromKeyCount = (results[results.keys[results.startIndex.advancedBy(i)]] as Array<DataModel>).count
    for j in 0...(valueFromKeyCount-1) {
         let dm = results[results.keys[results.startIndex.advancedBy(i)]][j] as DataModel
         print(dm.name) 
    }
}
Comments