Last active
August 29, 2015 14:22
-
-
Save jeremychone/d67f5ff365c6f55240f5 to your computer and use it in GitHub Desktop.
Swift Utitilies
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
// | |
// Future.swift | |
// | |
// Experimental simple Future/Promise class in Swift 2 (Beta) | |
// | |
// NEXT: probably want to split the promise (done/fail) from the future part (the resolve/reject) | |
// | |
// Jeremy Chone 2015-06-21 | |
import Foundation | |
public class Future<T> { | |
private var doneFunctions: [T -> Void] = [] | |
private var doneOnMainFunctions: [T -> Void] = [] | |
private var failFunctions: [ErrorType -> ()] = [] | |
private var val:T? | |
public init(){ | |
} | |
// MARK: Promise interface | |
public func done(success: (T -> Void)) -> Future<T>{ | |
doneFunctions.append(success) | |
return self | |
} | |
public func doneOnMain(success: (T -> Void)) -> Future<T>{ | |
doneOnMainFunctions.append(success) | |
return self | |
} | |
public func fail(fail: (ErrorType -> ())) -> Future<T>{ | |
failFunctions.append(fail) | |
return self | |
} | |
// MARK: Future interface | |
public func resolve(result: T) -> Future<T>{ | |
val = result | |
for fun in doneFunctions { | |
fun(result) | |
} | |
for fun in doneOnMainFunctions { | |
dispatch_async(dispatch_get_main_queue(),{ | |
fun(result) | |
}) | |
} | |
return self | |
} | |
public func reject(error: ErrorType) -> Future<T>{ | |
for fun in failFunctions{ | |
fun(error) | |
} | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for Swift 2 (beta). (Error Type)