Greg Robertson Greg Robertson - 1 year ago 69
Swift Question

Swift: Checking dictionary object type for Array

I am reading a JSON file that has some items that are arrays in one object but single stand alone values in others.

"name":"Red Truck",
"name":"Blue-Silver Truck",

I am pulling the JSON into a Dictionary.

if let path = NSBundle.mainBundle().pathForResource("theFile", ofType: "json")
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
{ // NSJSONReadingOptions.MutableContainers
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
if let trucks : [NSDictionary] = jsonResult["trucks"] as? [NSDictionary]
for truck: NSDictionary in trucks

Is there a way in swift to determine the type of object in the dictionary?



Answer Source

Yes, you can use optional binding and downcasting, like this:

if let trucks = jsonResult["trucks"] as? [[String:AnyObject]] {
    for truck in trucks {
        if let colourString = truck["colour"] as? String {
            // it's a String
        } else if let colourArray = truck["colour"] as? [String] {
            // it's an Array of Strings
        } else {
            // it's something else or nil
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download