withCheckedThrowingContinuation当没有返回类型时,我无法编译。例如:
public\n func\n write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float)\n async\n throws\n {\n try await withCheckedThrowingContinuation\n // ^ Generic parameter \'T\' could not be inferred\n { inCont in\n self.workQ.async\n {\n do\n {\n self.deviceID = inDeviceID\n try self.write(address: inAddr, value: inVal)\n inCont.resume()\n }\n \n catch (let e)\n {\n inCont.resume(throwing: e)\n }\n }\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n返回的版本工作得很好:
\n public\n func\n readRegister(address inAddr: Int, fromDevice inDeviceID: Int)\n async\n throws\n -> UInt16\n {\n try await withCheckedThrowingContinuation\n { inCont in\n self.workQ.async\n {\n do\n {\n self.deviceID = inDeviceID\n let r = try self.readRegister(address: inAddr)\n inCont.resume(returning: r)\n }\n \n catch (let e)\n {\n inCont.resume(throwing: e)\n }\n }\n }\n }\nRun Code Online (Sandbox Code Playgroud)\n
Ric*_*ick 23
当我写这篇文章时,我发现像这样明确的工作:
public
func
write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float)
async
throws
{
try await withCheckedThrowingContinuation
{ (inCont: CheckedContinuation<Void, Error>) -> Void in
self.workQ.async
{
do
{
self.deviceID = inDeviceID
try self.write(address: inAddr, value: inVal)
inCont.resume()
}
catch (let e)
{
inCont.resume(throwing: e)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我向 Apple 提交了一个错误。
小智 12
如果您return之前使用try await它应该可以工作。我真的不明白为什么,因为在这种情况下不需要退货,但它对我有效。
public
func
write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float)
async
throws
{
return try await withCheckedThrowingContinuation
{ inCont in
self.workQ.async
{
do
{
self.deviceID = inDeviceID
try self.write(address: inAddr, value: inVal)
inCont.resume()
}
catch (let e)
{
inCont.resume(throwing: e)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想我应该添加另一个例子
extension Something {
public func sync() async throws {
// The swift compiler demands that we be explicit where there is no return type.
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) -> Void in
self.sync { result in
switch result {
case .success(let entry):
continuation.resume(with: .success(entry))
case .failure(let error):
continuation.resume(with: .failure(error))
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:Xcode 现在可以使用 async/await 延续来包装基于闭包的函数。
| 归档时间: |
|
| 查看次数: |
6104 次 |
| 最近记录: |