Can we handle key paths (like the ones we’re used to in NSDictionary) while parsing JSON? That would be cool right? So, why wait, let’s implement it.
Posts in this series:
We defined a method,
parseMember, method takes a Dictionary, parses it and returns a
Member. This method can’t deal with whole JSON response that we can see above. It can only handle dictionary objects under
So, the question now is, how do we extract only the value of
Using key paths.
Currently, there is no support for it in Swift Dictionaries. Our only option is to cast the Swift Dictionary to
NSDictionary and use its
Because values in
box are of type
AnyObject we used generics to cast the value property when returning.
Where do we use this method?
The ideal place to use this
keyPath function is during transformations ie., while using
<<~, depending on whether we are talking about a single dictionary or array of dictionaries.
The problem is,
keyPath function that we wrote above is not compatible with any of those transformation operators.
If you look at the definition of
<~~ operator, the function
keyPath in our case now) is of type
A -> B?. But our
keyPath is of type
([String: AnyObject], String) -> T? which is wrong. It should be
[String: AnyObject] -> T?, because that is what we get from
That means, our
keyPath method should only take one parameter,
[String: AnyObject], to be compatible with our operators.
Then how can we pass the
Saw what I did there? We can invoke
keyPath("our.key.path") which returns us a partially applied function that takes a parameter of type
[String: AnyObect]. Exactly what we need.
For testing, let’s try to extract the
The above code should print the value
Optional("National Savings"). Sweet…
Let’s start the parsing:
<~~ is used to get the
[String: AnyObject] and passed to
keyPath which extracts the value of key path. This extracted value is then casted to an array of
[String: AnyObject] and each dictionary is passed to
parseMember, results are collected and returned.
There you go, we’ve successfully retrieved values through key path and parsed it. Woohoh..!
You can find the whole source code as Gist on GitHub