Created
February 5, 2015 18:52
-
-
Save chriseidhof/714951d851128c06bc05 to your computer and use it in GitHub Desktop.
MCE
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
// | |
// main.swift | |
// MCE | |
// | |
// Created by Chris Eidhof on 05/02/15. | |
// Copyright (c) 2015 Chris Eidhof. All rights reserved. | |
// | |
import Foundation | |
class Box<T> { | |
let unbox: T | |
init(_ value: T) { self.unbox = value } | |
} | |
enum Result<T> { | |
case Error(NSError) | |
case Success(Box<T>) | |
} | |
let myURL = NSURL(string: "http://localhost:8000/users/objcio") | |
func getData(url: NSURL) -> Result<NSData> { | |
var error: NSError? = nil | |
let optionalData = NSData(contentsOfURL: url, options: NSDataReadingOptions.allZeros, error: &error) | |
if let data = optionalData { | |
return .Success(Box(data)) | |
} else { | |
return .Error(error!) | |
} | |
} | |
typealias JSONDict = [String:AnyObject] | |
func parseJSON(data: NSData) -> Result<JSONDict> { | |
var error: NSError? = nil | |
if let obj = NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: &error) as? JSONDict { | |
return .Success(Box(obj)) | |
} else { | |
return .Error(error!) | |
} | |
} | |
func parsePublicRepos(dict: JSONDict) -> Result<Int> { | |
if let number = dict["public_repos"] as? Int { | |
return .Success(Box(number)) | |
} else { | |
let err = NSError(domain: "objc.io", code: 42, userInfo: [:]) | |
return .Error(err) | |
} | |
} | |
infix operator >>> { associativity left } | |
func >>><A,B>(value: Result<A>, f: A -> Result<B>) -> Result<B> { | |
switch value { | |
case .Error(let e): | |
return .Error(e) | |
case .Success(let boxed): | |
return f(boxed.unbox) | |
} | |
} | |
func getReposFromURL(url: NSURL) -> Result<Int> { | |
return getData(url) >>> parseJSON >>> parsePublicRepos | |
} | |
switch getReposFromURL(myURL!) { | |
case .Error(let e): | |
println(e.localizedDescription) | |
case .Success(let n): | |
println("SUCCESS! \(n.unbox)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment