LoginSignup
1
2

More than 1 year has passed since last update.

【Swift】Closureをasync/awaitにする

Posted at

はじめに

Closureをasync/awaitにしたく、やり方を調べてみました。

  • withCheckedContinuation
  • withCheckedThrowingContinuation
    を使うことで実現できるようです。

環境

Xcode 14.0

内容

withCheckedContinuation

func withCheckedContinuation<T>(
    function: String = #function,
    _ body: (CheckedContinuation<T, Never>) -> Void
) async -> T

👇のように使う

func hoge() async -> String {
    await withCheckedContinuation({ continuation in
        // ここでClosureの処理
        // 最後にcontinuation.resume()をして結果を返す
    })
}

withCheckedThrowingContinuation

func withCheckedThrowingContinuation<T>(
    function: String = #function,
    _ body: (CheckedContinuation<T, Error>) -> Void
) async throws -> T

👇のように使う

func hoge() async throws -> String {
    try await withCheckedContinuation({ continuation in
        // ここでClosureの処理をする
        // 最後にcontinuation.resume()をして結果を返す
    })
}

CheckedContinuation

struct CheckedContinuation<T, E> where E : Error
  • resume(returning:)
    func resume(returning value: T)
    継続待ちのタスクを中断点から正常に復帰させることで再開させる
  • resume(throwing:)
    func resume(throwing error: E)
    継続待ちのタスクに中断点からエラーを投げさせて再開させる
  • resume(with:)
    func resume(with result: Result<T, E>)
    与えられたResult値の状態に応じて、正常に戻るかエラーを投げるかして継続待ちのタスクを再開させる

さいごに

とても簡単でしたが、async/awaitに対応するライブラリも増えてきて使う機会は減ってきそうですね。

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2