Skip to content

Instantly share code, notes, and snippets.

@gfontenot
Created February 19, 2015 15:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfontenot/92e5b69f0c0b162ab19b to your computer and use it in GitHub Desktop.
Save gfontenot/92e5b69f0c0b162ab19b to your computer and use it in GitHub Desktop.
example of decoding dictionary objects with Argo/FP
import Argo
import Runes
func +<T, V>(lhs: [T: V], rhs: [T: V]) -> [T: V] {
var dict = lhs
for (key, val) in rhs {
dict[key] = val
}
return dict
}
func decodeDict<T>(j: JSONValue) -> [String: T]? {
switch j {
case let .JSONObject(xs):
return reduce(xs, [:]) { (accum, pair) in
if let x: T = pair.1.value(), xs = accum {
return xs + [pair.0: x]
}
return accum
}
default: return .None
}
}
struct Notifications: JSONDecodable {
let email: [String: Bool]
let push: [String: Bool]
static func create(email: [String: Bool])(push: [String: Bool]) -> Notifications {
return Notifications(email: email, push: push)
}
static func decode(j: JSONValue) -> Notifications? {
let email: [String: Bool]? = j["email"] >>- decodeDict
let push: [String: Bool]? = j["push"] >>- decodeDict
return Notifications.create
<^> email
<*> push
}
}
let json: AnyObject = [ "notifications" : [[
"email": [
"balance": true,
"guest_joins": true,
"low_battery": false
],
"push": [
"balance": true,
"guest_joins": true,
"low_battery": true
]
]]]
let val = JSONValue.parse(json)["notifications"]
let notifications: [Notifications]? = val >>- JSONValue.mapDecode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment