This article is an excerpt from Parsing JSON in Swift.
When you’re casting types as you parse your JSON, be as specific as you can to reduce clutter. This is especially important when working with arrays, which generally contain just one type. Let’s look at how we might parse the following JSON (from the GitHub Search Repositories API):
{
"total_count": 78457,
"incomplete_results": false,
"items": [
{
"id": 22458259,
"name": "Alamofire",
"description": "Elegant HTTP Networking in Swift"
}
]
}
For now, let’s assume we have a parseRepository
method with the following signature:
func parseRepository(json: [String: AnyObject]) -> Repository?
This should take a JSON dictionary that represents a repository and convert it into our Repository
model object.
Now, if we want to get the repository out of the items array and transform it into our model object, we might try something like this:
if let items = json["items"] as? [AnyObject],
item = items[0] as? [String: AnyObject] {
parseRepository(item)
}
We start by casting our items
to an array containing elements of type AnyObject
. Then, since our parseRepository
method requires a dictionary ([String: AnyObject]
), we’re forced to cast item
– the first element of our array – to a [String: AnyObject]
. This extra line is unnecessary clutter – it’s an extra cast that we don’t need. And it’s all because we started by casting items
to [AnyObject]
. (Note that casting to NSArray
causes exactly the same issue.)
Instead, we can just cast items
to the type we expect, which is more specific than an array of objects – it’s an array of dictionaries.
if let items = json["items"] as? [[String: AnyObject]] {
parseRepository(items[0])
}
This allows us to call parseRepository
without an additional cast, since accessing any element of the items array will yield a dictionary.
But now the cast to [[String: AnyObject]]
is hard to read due to the all the square brackets. Is it an array or a dictionary? It’s hard to tell at first glance. Can we get rid of a pair of square brackets and make it clear that we’re working with an array of dictionaries and not just a dictionary?
Frustrated with how much work it seems to be just to fill a table view with JSON data? Imagine getting it done in an afternoon and being confident that it works exactly the way you want it to, thanks to the automated tests you have in place. You can learn how to build and test your JSON parser with Parsing JSON in Swift and be sure it can handle any JSON that comes its way. Start Parsing JSON in Swift now and save $10 off the full price by getting the prerelease version today.