Greg Robertson
Greg Robertson

Reputation: 2347

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.

{
    "trucks":[
       {
           "name":"Red Truck",
           "colour":"Red"
       },
       {
           "name":"Blue-Silver Truck",
           "colour":[
                      "blue",
                      "silver"
           ]
       }
 }

I am pulling the JSON into a Dictionary.

   if let path = NSBundle.mainBundle().pathForResource("theFile", ofType: "json")
    {
        do
        {
            let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
            do
            {  // 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?

Thanks

Greg

Upvotes: 1

Views: 497

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

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
        }
    }
}

Upvotes: 4

Related Questions