Alec O'Connor Alec O'Connor - 6 months ago 17
iOS Question

Copying a dictionary into an array in Swift

I am attempting to create an array of dictionaries using [[String:AnyObject]]. I have used SwiftyJSON to convert JSON into a JSON object and am able to loop through each key and value. The code below will not create an individual business for each business, but an individual business for each key and value in the businesses. Currently the JSON has sections for id, name, latitude, and longitude and I want each of these values in the dictionary for each business in the array.

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

for business in json["businesses"]!.array! {
for (key,value) in business {
let value1 = value.stringValue
businesses.append([key:value1])
}
}


How can I adjust this code to create an individual business for each business, instead of an individual business in the array for each key and value.

Currently:

businesses[:] = ["id" = 1, "name" = "asdf",...,"id" = 2, "name" = "asdf2"]


Instead of what I want which is

businesses[0] = ["id" = 1, "name" = "asdf"]
businesses[1] = ["id" = 2, "name" = "asdf2"]

Answer

Basiclly, you just need to add the key, value pair for each busines to a dictionary and then add that dictionary to your array.

Something like this:

var businesses = [[String: AnyObject]]
        for business in json["businesses"]!.array! {
            var dic = [String: AnyObject]
            for (key,value) in business {
                let value1 = value.stringValue
                dic [key] = value1
            }
            businesses.append(dic)
        }

Well, I couldn't test the code 100% since you didn't provide your JSON data, but this is the general idea.

Comments