/*:#localized(key: "GettingAValueBack")
 # Getting a value back

 A task can *return* a value, and you read it by `await`-ing its `value` property.
 Because the work may still be running, reading the value is itself an `await`.
 */
//#-editable-code
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func pullEspresso() async -> String {
    try? await Task.sleep(for: .milliseconds(400))
    return "a double espresso"
}

Task {
    let order = Task {
        await pullEspresso()
    }

    print("Order placed; barista is working")
    let cup = await order.value          // suspend until the task finishes
    print("Served: \(cup)")
    PlaygroundPage.current.finishExecution()
}
//#-end-editable-code
/*:#localized(key: "GettingAValueBack-2")
 **Watch it run:** `Order placed...` prints first, then a pause, then `Served: a
 double espresso`. The outer task suspended at `await order.value` until the inner
 task produced its result, then picked up exactly where it left off.

 If the task can throw, `value` throws too, so you write `try await task.value`.
 When you'd rather inspect the outcome without a `do-try-catch`, reach for
 `task.result`, which hands you a `Result` you can switch on:

 ```swift
 enum BarError: Error { case outOfBeans }

 Task {
     let order = Task { () -> String in
         try await Task.sleep(for: .milliseconds(200))
         throw BarError.outOfBeans
     }

     switch await order.result {
     case .success(let cup): print("Served: \(cup)")
     case .failure(let error): print("Couldn't serve: \(error)")
     }
 }
 ```

 `await order.result` never throws; the error is *inside* the `Result`. You'll see
 `Couldn't serve: outOfBeans`.

 [Previous](@previous)  |  page 3 of 11  |  [Next: Structured vs Unstructured](@next)
 */
