Created
February 19, 2015 15:38
-
-
Save gfontenot/92e5b69f0c0b162ab19b to your computer and use it in GitHub Desktop.
example of decoding dictionary objects with Argo/FP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
<*> 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