小编Jer*_*ere的帖子

并发执行代码中捕获的 var 的突变

我在 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)

它会编译。我知道这个错误是为了防止数据竞争,但为什么移动变量会使其安全?

async-await swift xcode14

20
推荐指数
2
解决办法
1万
查看次数

标签 统计

async-await ×1

swift ×1

xcode14 ×1