How to capture local variable inside an async closure in Swift?

To prevent data races you must use synchronized access to variables from concurrent operations and the compiler doesn’t allow you to change your array directly. To avoid the issue you can implement isolated access to your data with an actor instance e.g.:

actor Store {
    var reviewIds: [Int] = []
    func append(ids: [Int]) {
        reviewIds.append(contentsOf: ids)
    }
}

func getReviewIds() {
    
    let store = Store()
    
    Task {
        let ids = await getReviewIdsFromGoogle()
        await store.append(ids: ids)
        print(await store.reviewIds)
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)