Swift async/await 既存の非同期処理をasyncに変換するには?

Updated
Mar 15, 2021 6:39 PM
Created
Feb 4, 2021 8:16 AM
Tags
Swift
Keywords

2021/01/24時点のsnapshotでは多分このようにかける

withUnsafeContinuation を使う感じ

func asyncOperation() async -> Int {
  await withUnsafeContinuation { continuation in
    classicAsyncOperation { value in
      continuation.resume(returning: value)
    }
  }
}

func classicAsyncOperation(_ completion: @escaping (Int) -> Void) {
  DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    completion(10)
  }
}

func operation() async -> OperationResult {
  // Suspend the current task, and pass its continuation into a closure
  // that executes immediately
  return await withUnsafeContinuation { continuation in
    // Invoke the synchronous callback-based API...
    beginOperation(completion: { result in
      // ...and resume the continuation when the callback is invoked
      continuation.resume(returning: result)
    }) 
  }
}