Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct User {
- let id: Int
- let name: String
- let email: String?
- }
- extension User: JSONDecodable {
- static func create(id: Int, name: String, email: String?) -> User {
- return User(id: id, name: name, email: email)
- }
- static func decode(json: JSONValue) {
- return check(User.create, json["id"], json["name"], json["email"])
- // check() calls its fn only if the required arguments are non-nil
- // You could readily define check() as an infix operator that takes a tuple, e.g.:
- // return User.create?<(json["id"], json["name"], json["email"])
- }
- }
- protocol JSONDecodeable {
- class func decode(json: JSONValue) -> Self?
- }
- enum JSONValue {
- case JSONObject([String: JSONValue])
- case JSONArray([JSONValue])
- // etc
- subscript(key: String) -> Int {}
- subscript(key: String) -> Bool {}
- // etc
- }
- func check<A, B, C, R>(fn: (A,B,C) -> R, a: A?, b: B?, c: C?) -> R? {
- if a == nil || b == nil || c == nil {
- return nil
- } else {
- return fn(a!, b!, c!)
- }
- }
- func check<A, B, C, R>(fn: (A?,B,C) -> R, a: A?, b: B?, c: C?) -> R? {
- if b == nil || c == nil {
- return nil
- } else {
- return fn(a, b!, c!)
- }
- }
- func check<A, B, C, R>(fn: (A,B?,C) -> R, a: A?, b: B?, c: C?) -> R? {
- if a == nil || c == nil {
- return nil
- } else {
- return fn(a!, b, c!)
- }
- }
- func check<A, B, C, R>(fn: (A,B,C?) -> R, a: A?, b: B?, c: C?) -> R? {
- if a == nil || b == nil {
- return nil
- } else {
- return fn(a!, b!, c)
- }
- }
- func check<A, B, C, R>(fn: (A?,B?,C) -> R, a: A?, b: B?, c: C?) -> R? {
- if c == nil {
- return nil
- } else {
- return fn(a, b, c!)
- }
- }
- func check<A, B, C, R>(fn: (A?,B,C?) -> R, a: A?, b: B?, c: C?) -> R? {
- if b == nil {
- return nil
- } else {
- return fn(a, b!, c)
- }
- }
- func check<A, B, C, R>(fn: (A,B?,C?) -> R, a: A?, b: B?, c: C?) -> R? {
- if a == nil {
- return nil
- } else {
- return fn(a!, b, c)
- }
- }
- func check<A, B, C, R>(fn: (A?,B?,C?) -> R, a: A?, b: B?, c: C?) -> R? {
- return fn(a, b, c)
- }
- // etc.
Add Comment
Please, Sign In to add comment