我想创建一个 URL 请求并将其传递给 async let 绑定,这对我来说似乎很自然:
func test() async {
// Force unwraps (!) are just for demo
var request = URLRequest(url: URL(string:"https://stackoverflow.com")!)
request.httpMethod = "GET" // just for example
// some more tinkering with `request` here.
// Error on this line: "Reference to captured var 'request' in concurrently-executing code"
async let responseData = URLSession.shared.data(for: request).0
// It works like this:
// let immutableRequest = request
// async let responseData = URLSession.shared.data(for: immutableRequest).0
// other stuff
print("Response body: \(String(data: try! await responseData, encoding: .utf8))")
}
为什么我会收到错误消息?URLRequest
是一个结构,所以当我们将它传递给一个函数时,该函数应该得到该结构的副本,所以如果我request
在异步调用之后修改,它不应该影响调用。
我知道调用是异步发生的,但我希望它在调用点捕获参数,然后继续执行,就好像调用已经进行一样(因此,request
调用点的副本已传递到data(for: request)
.
此外,是否有一种方便的方法可以在不创建另一个let
变量且不使用闭包进行初始化的情况下执行此操作request
,例如:
let request: URLRequest = {
var result = URLRequest(url: URL(string:"https://stackoverflow.com")!)
result.httpMethod = "GET"
return result
}()