Skip to content

Instantly share code, notes, and snippets.

@jordanekay
Forked from andymatuschak/gist:2b311461caf740f5726f
Last active August 29, 2015 14:12
Show Gist options
  • Save jordanekay/e33b41d78161bfdfdbaf to your computer and use it in GitHub Desktop.
Save jordanekay/e33b41d78161bfdfdbaf to your computer and use it in GitHub Desktop.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment