I am filling a dict with values from json:
var dict = Dictionary<String, AnyObject>()
dict["venue"] = json["info"]["venue"].string!
dict["addressStreet"] = json["info"]["addressStreet"].string!
dict["capacity"] = json["info"]["capacity"].int!
dict["mascot"] = json["info"]["mascot"].string!
dict["foodService"] = json["info"]["foodService"].boolean!
Imagine the values from the json are:
//Smith Concert Hall (a string)
//1234 Main Street (a string)
//150 (a number)
//no mascot listed - a null value
//true for food service - a boolean value
In case it has a bearing on this question, I am using SwiftyJSON to access the items in json. Info on SwiftyJSON is here: https://github.com/SwiftyJSON/SwiftyJSON
So, in this example we are dealing with several different types, such as strings, ints, booleans, and the chance of null values.
The json I am working on doesn't just have 5 items like in the above example. It has many. So, for an efficient program, I have done the following:
for (indexCount, element) in enumerate(appDelegate.json["info"]){
dict[element.0] = json["info"][element.0]
}
Which means instead of creating specific assignment statements for all possibilities, I am looping through and creating a tuple from each json item. The tuple contains the key and value. With that key and value I am automatically setting the key and value of the dict items.
BUT - when I go to use the dict item later, there is a problem. For example, if I try to do this, I get nil:
let a = dict["capacity"] as? String
println(a) //results with: nil
let b = dict["capacity"]
println("\(b)") //results with: nil
let c = String(stringInterpolationSegment: dict["capacity"])
println(c) //results with: nil
So to recap: If I am filling an "String, AnyObject" dictionary by enumerating through a json array with different value types... what can I do on the front or back end of this process to avoid errors and have useful data? In particular, strings seem to work fine, but when I encounter an int and try to cast it as a string (I have tried several ways) it fails all together or returns nil.
Thank you.