2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftAdvent Calendar 2023

Day 3

[Swift] CLIアプリでのasync functionのデバッグにはtop-level-awaitが使える

Last updated at Posted at 2023-12-02

背景

CLIアプリでasync functionをデバッグしたい時

Task.initではクロージャーの終了を待たないので結果が不安定になったり、そもそも結果が出なかったりします。

func doSomething() async {
    ...
    print("end")
}

Task {
    await doSomething()
}

解決策

Swift 5.7以降

top-level awaitが使えます。

func doSomething() async {
    ...
    print("end")
}

await doSomething()

Swift 5.5.2〜

func doSomething() async {
    ...
    print("end")
}

@main struct Main {
    static func main() async {
        await doSomething()
    }
}

2
1
2

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?