|
| 1 | +//: Playground - noun: a place where people can play |
| 2 | + |
| 3 | +import Cocoa |
| 4 | +import XCPlayground |
| 5 | + |
| 6 | +// |
| 7 | +// NOTE: custom framework needs to be built first (and restart Xcode if needed) |
| 8 | +// |
| 9 | +// Importing Custom Frameworks Into a Playground |
| 10 | +// https://developer.apple.com/library/prerelease/ios/recipes/Playground_Help/Chapters/ImportingaFrameworkIntoaPlayground.html |
| 11 | +// |
| 12 | +import SwiftTask |
| 13 | + |
| 14 | +typealias Progress = Float |
| 15 | +typealias Value = String |
| 16 | +typealias Error = NSError |
| 17 | + |
| 18 | +typealias MyTask = Task<Progress, Value, Error> |
| 19 | + |
| 20 | +let myError = NSError(domain: "MyErrorDomain", code: 0, userInfo: nil) |
| 21 | + |
| 22 | +//-------------------------------------------------- |
| 23 | +// Example 1: Sync fulfilled -> success |
| 24 | +//-------------------------------------------------- |
| 25 | + |
| 26 | +let task = MyTask(value: "Hello") |
| 27 | + .success { value -> String in |
| 28 | + return "\(value) World" |
| 29 | + } |
| 30 | + .success { value -> String in |
| 31 | + return "\(value)!!!" |
| 32 | + } |
| 33 | + |
| 34 | +task.value |
| 35 | + |
| 36 | +//-------------------------------------------------- |
| 37 | +// Example 2: Sync rejected -> success -> failure |
| 38 | +//-------------------------------------------------- |
| 39 | + |
| 40 | +let task2a = MyTask(error: myError) |
| 41 | + .success { value -> String in |
| 42 | + return "Never reaches here..." |
| 43 | + } |
| 44 | +let task2b = task2a |
| 45 | + .failure { error, isCancelled -> String in |
| 46 | + return "ERROR: \(error!.domain)" // recovery from failure |
| 47 | + } |
| 48 | + |
| 49 | +task2a.value |
| 50 | +task2a.errorInfo |
| 51 | +task2b.value |
| 52 | +task2b.errorInfo |
| 53 | + |
| 54 | +//-------------------------------------------------- |
| 55 | +// Example 3: Sync fulfilled or rejected -> then |
| 56 | +//-------------------------------------------------- |
| 57 | + |
| 58 | +// fulfills or rejects immediately |
| 59 | +let task3a = MyTask { progress, fulfill, reject, configure in |
| 60 | + if arc4random_uniform(2) == 0 { |
| 61 | + fulfill("Hello") |
| 62 | + } |
| 63 | + else { |
| 64 | + reject(myError) |
| 65 | + } |
| 66 | +} |
| 67 | +let task3b = task3a |
| 68 | + .then { value, errorInfo -> String in |
| 69 | + if let errorInfo = errorInfo { |
| 70 | + return "ERROR: \(errorInfo.error!.domain)" |
| 71 | + } |
| 72 | + |
| 73 | + return "\(value!) World" |
| 74 | + } |
| 75 | + |
| 76 | +task3a.value |
| 77 | +task3a.errorInfo |
| 78 | +task3b.value |
| 79 | +task3b.errorInfo |
0 commit comments