Skip to content

Instantly share code, notes, and snippets.

Created September 20, 2016 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/a65b6cbf7e1ebd9551ef1381485cf8bf to your computer and use it in GitHub Desktop.
Save anonymous/a65b6cbf7e1ebd9551ef1381485cf8bf to your computer and use it in GitHub Desktop.
Optional Parsing
import Foundation
typealias JSONKey = String
typealias JSONValue = AnyObject
typealias JSON = [JSONKey: JSONValue]
func transform<T, R>(value: T) -> R? {
return value as? R
}
func toJSON<T>(value: T) -> JSON? {
return transform(value)
}
extension Optional {
func apply<T>(f: (Wrapped -> T)?) -> T? {
if let value = self, function = f {
return function(value)
} else {
return .None
}
}
}
extension Dictionary {
func extract<T>(key: Key) -> T? {
return transform(self[key])
}
}
infix operator |> { associativity left } // pipe
func |><A, B>(value: A, f: A -> B) -> B {
return f(value)
}
infix operator >>- { associativity left } // flatMap
func >>-<A, B>(value: A?, f: A -> B?) -> B? {
return value.flatMap(f)
}
infix operator <^> { associativity left } // map
func <^><A, B>(f: A -> B, value: A?) -> B? {
return value.map(f)
}
infix operator <*> { associativity left } // apply
func <*><A, B>(f: (A -> B)?, value: A?) -> B? {
return value.apply(f)
}
func curry<A, B, C, R>(f: (A, B, C) -> R) -> A -> B -> C -> R {
return { a in
{ b in
{ c in
f(a, b, c)
}
}
}
}
struct User {
let id: Int
let name: String
let email: String?
static let create = curry(User.init)
}
let jsonOptional: NSDictionary? = ["id" : 1, "name" : "Vasia", "email" : "aaa@mail.com"]
let user = jsonOptional |> toJSON >>- { json in
return User.create
<^> json.extract("id")
<*> json.extract("name")
<*> json.extract("email")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment