2025-02-07 10:15:13
,某些文章具有时效性,若有错误或已失效,请在下方留言。Swift’s async let
syntax provides short, helpful syntax for running lots of work concurrently, allowing us to wait for them all later on. However, it only works as async let
– it’s not possible to use async var
.
Swift 的 async let
语法为并发运行大量工作提供了简短而有用的语法,允许我们稍后等待它们。但是,它只能作为 async let
工作 —— 不能使用 async var
。
If you think about it, this restriction makes sense. Consider pseudocode like this:
如果您仔细想想,这个限制是有道理的。考虑这样的伪代码:
func fetchUsername() async -> String {
// complex networking here
"Taylor Swift"
}
async var username = fetchUsername()
username = "Justin Bieber"
print("Username is \(username)")
That attempts to create a variable asynchronously, then writes to it directly. Have we cancelled the async work? If not, when the async work completes will it overwrite our new value? Do we still need to use await
when reading the value even after we’ve explicitly set it?
这会尝试异步创建一个变量,然后直接写入它。我们取消了异步工作吗?如果不是,当异步工作完成时,它会覆盖我们的新值吗?即使我们已经显式设置了该值,在读取该值时,我们是否仍然需要使用 await
?
This kind of code would create all sorts of confusion, so it’s just not allowed – async let
is our only option.
这种代码会产生各种混乱,所以它是不允许的——async let
是我们唯一的选择。
暂无评论内容