在Swift 5.5中组成同步和异步功能

发布于 2025-02-14 00:30:22 字数 322 浏览 1 评论 0原文

考虑以下(愚蠢的)示例:

func u () async -> UInt32 {
    let r =  UInt32(Int.random(in: 1...10))
    sleep(r)
    return r
}

func v(_ x: UInt32) -> UInt32 {
    x
}

Task.init{
    print(v(await u()))
    print(await v(u()))
    await print(v(u()))
}

任务中的所有三行似乎都起作用。它们是等效的,还是我应该知道任何陷阱?谢谢。

Consider the following (silly) example:

func u () async -> UInt32 {
    let r =  UInt32(Int.random(in: 1...10))
    sleep(r)
    return r
}

func v(_ x: UInt32) -> UInt32 {
    x
}

Task.init{
    print(v(await u()))
    print(await v(u()))
    await print(v(u()))
}

All three lines in the task appear to work. Are they equivalent, or are there any pitfalls I should be aware of? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

格子衫的從容 2025-02-21 00:30:22

喜欢尝试,Swift允许您将等待关键字放在表达式的任何部分,其中包含async方法:

func ƒ<T>(_ v: T) -> T { v }


// All equivalent:
func somethingThatThrows() throws {}
print(ƒ(try somethingThatThrows()))
print(try ƒ(somethingThatThrows()))
try print(ƒ(somethingThatThrows()))


// All equivalent:
func someAsyncFunc() async {}
Task {
    print(ƒ(await someAsyncFunc()))
    print(await ƒ(someAsyncFunc()))
    await print(ƒ(someAsyncFunc()))
}

// await applies to both function calls
sum = await someAsyncFunction() + anotherAsyncFunction()

// await applies to both function calls
sum = await (someAsyncFunction() + anotherAsyncFunction())

// Error: await applies only to the first function call
sum = (await someAsyncFunction()) + anotherAsyncFunction()

Like try, Swift allows you to place the await keyword on any part of an expression that contains an async method:

func ƒ<T>(_ v: T) -> T { v }


// All equivalent:
func somethingThatThrows() throws {}
print(ƒ(try somethingThatThrows()))
print(try ƒ(somethingThatThrows()))
try print(ƒ(somethingThatThrows()))


// All equivalent:
func someAsyncFunc() async {}
Task {
    print(ƒ(await someAsyncFunc()))
    print(await ƒ(someAsyncFunc()))
    await print(ƒ(someAsyncFunc()))
}

The Swift grammar reference for the await keyword does have an example for where placement of await does matter (awaiting only a subexpression of a whole expression that needs to be awaited), but it's not quite relevant here:

// await applies to both function calls
sum = await someAsyncFunction() + anotherAsyncFunction()

// await applies to both function calls
sum = await (someAsyncFunction() + anotherAsyncFunction())

// Error: await applies only to the first function call
sum = (await someAsyncFunction()) + anotherAsyncFunction()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文