[英]Swift async/await what it the replacement of DispatchQueue.main.async
[英]Cannot find in scope in swift in DispatchQueue.main.async
我在 SWift 中有这个代码:
import UIKit
import Foundation
func whatever() async -> Int{
return 2;
}
func test(){
Task.init{
var testing:Int = 0
do {
testing = try await whatever()
}
catch {
print("some error happened")
}
}
DispatchQueue.main.async {
print("from dispa")
if(testing == 0){
print("testing was never set")
}
}
}
test()
这是一个游乐场,在运行它时,我在DispatchQueue
的 if 语句中的Cannot find 'testing' in scope
我究竟做错了什么? 在 Task.init 中移动代码会引发不同的错误: Reference to captured var 'testing' in concurrently-executing code
变量testing
现在在Task.init
scope 中声明,这意味着DispatchQueue
闭包无法访问它。 要在两个闭包中使用它,您必须将它移动到 scope 中,两个闭包都可以访问它(即共享父范围)。
一旦你这样做了,我会说你想要在这里发生什么有点不清楚,但我猜这就是你正在寻找的结果。 请注意,您应该小心混合Task
和DispatchQueue
——它们是不同的范例,不一定会导致您认为的结果。
var testing = 0
func whatever() async throws -> Int {
return 2 //note that nothing async or throwing is actually happening here
}
func test(){
Task {
do {
testing = try await whatever()
}
catch {
print("some error happened")
}
}
DispatchQueue.main.async {
print("from dispatch")
if testing == 0 {
print("testing was never set")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.