我在 Swift 5.5 中遇到了问题,但我不太明白解决方案。
import Foundation
func testAsync() async {
var animal = "Dog"
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
animal = "Cat"
print(animal)
}
print(animal)
}
Task {
await testAsync()
}
Run Code Online (Sandbox Code Playgroud)
这段代码会导致错误
Mutation of captured var 'animal' in concurrently-executing code
Run Code Online (Sandbox Code Playgroud)
但是,如果将animal变量移离此异步函数的上下文,
import Foundation
var animal = "Dog"
func testAsync() async {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
animal = "Cat"
print(animal)
}
print(animal)
}
Task {
await testAsync()
}
Run Code Online (Sandbox Code Playgroud)
它会编译。我知道这个错误是为了防止数据竞争,但为什么移动变量会使其安全?