Skip to content

Instantly share code, notes, and snippets.

@swift2931
Created January 26, 2019 05:31
Show Gist options
  • Save swift2931/5cfa924eaeb7a590300718d628797438 to your computer and use it in GitHub Desktop.
Save swift2931/5cfa924eaeb7a590300718d628797438 to your computer and use it in GitHub Desktop.
A future promise without inheritance
import UIKit
struct Future<U> {
var u: U? {
didSet {
promise?(u)
}
}
var promise: ((U?) -> ())?
func then<V>(_ action: @escaping (U?, Future<V>) -> ()) -> Future<V> {
let p = Promise(action, self)
return p.fv
}
}
struct Promise<U, V> {
var fu: Future<U>
let fv: Future<V>
init(_ action: @escaping (U?, Future<V>) -> (), _ fu: Future<U> = Future<U>(), _ fv: Future<V> = Future<V>()) {
self.fu = fu
self.fv = fv
let p: (U?) -> () = { u in
action(u, fv)
}
self.fu.promise = p
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment