Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
{
"status": 200,
"response": {
"request_id": 1386,
"result": {
"department_name": "National Savings",
"members": [
{
"member_id": 0,
"name": "Essie Ferrell"
},
{
"member_id": 1,
"name": "Jaclyn Oneill"
},
{
"member_id": 2,
"name": "Forbes Tillman"
},
{
"member_id": 3,
"name": "Fry Odonnell"
},
{
"member_id": 4,
"name": "Ball Frazier"
}
]
}
}
}
import Foundation
func get<T>(box:[String: AnyObject], key: String) -> T? {
return box[key] as? T
}
func get<T>(item: AnyObject) -> T? {
return item as? T
}
func keyPath<T>(path: String) -> (box: [String: AnyObject]) -> T? {
return { box in
return (box as NSDictionary).valueForKeyPath(path) as? T
}
}
import Foundation
guard let data = NSData(contentsOfFile: "departments.json"),
let jsonDictionary = try? NSJSONSerialization.JSONObjectWithData(data, options: []) else {
print("Couldn't load JSON file")
exit(1)
}
func parseMember(data: [String: AnyObject]) -> Member? {
return makeMember <*> get(data, key: "member_id")
<*> get(data, key: "name")
}
let department: String? = get(jsonDictionary) <~~ keyPath("response.result.department_name")
let members = get(jsonDictionary) <~~ keyPath("response.result.members") <<~ parseMember
print(department)
print(members)
import Foundation
struct Member {
let memberID: Int
let name: String
}
func makeMember(memberID: Int) -> (name: String) -> Member {
return { name in
return Member(memberID: memberID, name: name)
}
}
infix operator <*> {
associativity left
precedence 100
}
infix operator <?> {
associativity left
precedence 100
}
infix operator <~~ {
associativity left
precedence 110
}
infix operator <<~ {
associativity left
precedence 110
}
func <*><A, B>(f: (A -> B)?, x: A?) -> B? {
guard let f = f, x = x else {
return nil
}
return f(x)
}
func <?><A, B>(f: (A? -> B)?, x: A?) -> B? {
guard let f = f else {
return nil
}
return f(x)
}
func <~~<A, B>(x: A?, f: (A -> B?)) -> B? {
guard let x = x else {
return nil
}
return f(x)
}
func <<~<A, B>(x: [A]?, f: (A -> B?)) -> [B]? {
guard let x = x else {
return nil
}
return x.map(f).flatMap{ $0 }
}
_ _
| |__ | |__ __ _ _ __ __ _ __ ___ ____ _
| '_ \| '_ \ / _` | '__/ _` |/ _` \ \ / / _` |
| |_) | | | | (_| | | | (_| | (_| |\ V / (_| |
|_.__/|_| |_|\__,_|_| \__, |\__,_| \_/ \__, |
|___/ |___/
Just a dummy text file to have a proper titles for gists 😒
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment