我在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()
}
这段代码会导致错误
Mutation of captured var 'animal' in concurrently-executing code
但是,如果将animal
变量从此异步函数的上下文中移出,
import Foundation
var animal = "Dog"
func testAsync() async {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
animal = "Cat"
print(animal)
}
print(animal)
}
Task {
await testAsync()
}
它会编译的.我理解这个错误是为了防止数据竞争,但为什么移动变量会使它变得安全?