Last active
August 29, 2015 14:02
-
-
Save digal/11a482e47ee1b56c4b04 to your computer and use it in GitHub Desktop.
Syncronous data fetcher in swift
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
//@auto_closure hack to prevent `LLVM ERROR: unimplemented IRGen feature! non-fixed multi-payload enum layout` | |
//as in https://github.com/maxpow4h/swiftz/blob/master/swiftz/Either.swift | |
enum Either<L,R> { | |
case Left(@auto_closure () -> L) | |
case Right(@auto_closure () -> R) | |
func flatMapLeft<L1>(f: (L) -> Either<L1, R>) -> Either<L1, R> { | |
switch self { | |
case let .Left(l): return f(l()) | |
case let .Right(r): return .Right(r) | |
} | |
} | |
func flatMapRight<R1>(f: (R) -> Either<L, R1>) -> Either<L, R1> { | |
switch self { | |
case let .Left(l): return .Left(l) | |
case let .Right(r): return f(r()) | |
} | |
} | |
func flatMap<R1>(f: (R) -> Either<L, R1>) -> Either<L, R1> { | |
return self.flatMapRight(f) | |
} | |
func mapLeft<L1>(f: (L) -> L1) -> Either<L1, R> { | |
return self.flatMapLeft { | |
l -> Either<L1, R> in | |
return .Left(f(l)) | |
} | |
} | |
func mapRight<R1>(f: (R) -> R1) -> Either<L, R1> { | |
return self.flatMapRight { | |
r-> Either<L, R1> in | |
return .Right(f(r)) | |
} | |
} | |
var description:String { | |
switch self { | |
case let .Left(l): return "Left(\(l()))" | |
case let .Right(r): return "Right(\(r()))" | |
} | |
} | |
} | |
//TODO: timeout param | |
func syncFetch(url: NSURL) -> Either<NSError, NSData> { | |
let session = NSURLSession.sharedSession() | |
let semaphore = dispatch_semaphore_create(0); | |
var result: Either<NSError, NSData>? | |
let task = session.dataTaskWithURL(url, completionHandler: | |
{ data, response, error -> Void in | |
if let e = error { | |
result = Either.Left(e) | |
} else { | |
result = Either.Right(data) | |
} | |
dispatch_semaphore_signal(semaphore) | |
} | |
) | |
task.resume() | |
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) | |
return result! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment