This presentation was held at CocoaHeads Berlin.
I am explaining the concept of promise with help of OMPromise Library written in ObjC. In the end I present a non complete Swift implementation of Promises concept that I hacked together in couple of hours.
35. Using constants as read only property is not a good
idea as you have to set them directly in the
initializer
class Promise<T> {
let state : PromiseState
let result : T
let error : NSError
}
36. Switching to var makes it work but Promise is not
immutable any more
class Promise<T> {
var state : PromiseState
var result : T?
var error : NSError?
init(){
state = .Unfulfilled
}
func fulfill(value : T){
result = value
state = .Fulfilled
}
}
37. Trying to make a read only property
class Promise<T> {
var state : PromiseState
var result : T? {
get {
return self.result
}
}
var error : NSError?
init(){
state = .Unfulfilled
}
}
38. Sadly this was an infinite loop
— There are no Read-Only properties in Swift
— Only Read-Only Computed Properties
39. Schock number 2
— There are no ivars in Swift
— And no visibility constrains (but they promised
to introduced those)
41. func future<T>(execution : ()->FutureResult<T>)(handler: FutureHandler<T>) {
var result : FutureResult<T>?
var done = false
dispatch_async(dispatch_get_global_queue(0, 0)) {
result = execution()
done = true
}
dispatch_async(dispatch_get_global_queue(0, 0)) {
while !done {}
dispatch_async(dispatch_get_main_queue()) {
switch handler {
case .FulFilled(let fulfilled):
switch result! {
case .Result(let value):
fulfilled(value())
case .Error : println("can't process error")
}
case .Failed(let failed):
switch result! {
case .Result: println("can't process result")
case .Error(let error) : failed(error())
}
}
}
}
}
42. Main concept = currying
func add(n1:Int)(n2:Int) -> Int {
return n1 + n2
}
let increaseByTwo = add(2)
let sum = increaseByTwo(3)
43. Using enums with Associated Values
enum FutureHandler<T>{
case FulFilled((T)->())
case Failed((NSError)->())
}
enum FutureResult<T>{
case Result(@auto_closure ()->T)
case Error(@auto_closure ()->NSError)
}
44. Here is how you can use it:
var f = future {
FutureResult.Result(2 + 3)
}
f (handler: FutureHandler.FulFilled {
result in
println("Promise fulfilled : (result)")
})