PromiseK provides the Promise
class designed as a Monad for Swift.
// `flatMap` is equivalent to `then` of JavaScript's `Promise`
let a: Promise<Int> = asyncGet(2).flatMap { asyncGet($0) }.flatMap { asyncGet($0) }
let b: Promise<Int> = asyncGet(3).map { $0 * $0 }
let sum: Promise<Int> = a.flatMap { a0 in b.flatMap { b0 in Promise(a0 + b0) } }
// uses `Optional` for error handling
let mightFail: Promise<Int?> = asyncFailable(5).flatMap { Promise($0.map { $0 * $0 }) }
let howToCatch: Promise<Int> = asyncFailable(7).flatMap { Promise($0 ?? 0) }
// `>>-` operator is equivalent to `>>=` in Haskell
// can use `>>-` instead of `flatMap`
let a2: Promise<Int> = asyncGet(2) >>- { asyncGet($0) } >>- { asyncGet($0) }
// a failable operation chain with `>>-`
let failableChain: Promise<Int?> = asyncFailable(11) >>- { $0.map { asyncFailable($0) } }
// also `>>-?` operator is available
let failableChain2: Promise<Int?> = asyncFailable(11) >>-? { asyncFailable($0) }
Carthage is available to install PromiseK. Add it to your Cartfile:
github "koher/PromiseK" ~> 2.0
For iOS 8 or later,
- Put PromiseK.xcodeproj into your project in Xcode.
- Click the project icon and select the "General" tab.
- Add PromiseK.framework to "Embedded Binaries".
import PromiseK
in your swift files.
For iOS 7, put all swift files in the Source directory into your project.