Created
September 20, 2016 13:57
-
-
Save anonymous/a65b6cbf7e1ebd9551ef1381485cf8bf to your computer and use it in GitHub Desktop.
Optional Parsing
This file contains 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 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