Swift中withCheckedThrowingContinuation无返回值时泛型T无法推断编译问题
问题原因
withCheckedThrowingContinuation 是泛型函数,其泛型参数 T 代表 continuation 最终返回的值类型。
在带返回值的 readRegister 方法中,你调用了 inCont.resume(returning: r),编译器可以通过参数 r 的 UInt16 类型自动推导出泛型参数 T 为 UInt16,和方法的返回值匹配,因此编译正常。
而无返回值的 write 方法中,你调用的是无参数的 inCont.resume(),没有足够的类型信息供编译器推导泛型参数 T 的具体类型,因此触发了「Generic parameter 'T' could not be inferred」的编译错误。
解决方案
有两种常用的修复方式,任选其一即可:
- 显式声明泛型参数为
Void,直接告知编译器不需要返回值:只需要在withCheckedThrowingContinuation后添加<Void>标注。 - 调用
resume时显式返回Void类型的空值:将无参数的inCont.resume()替换为inCont.resume(returning: ()),编译器即可通过参数自动推导出T为Void。
修复后的代码示例:
public func write(toDevice inDeviceID: Int, atAddress inAddr: Int, value inVal: Float) async throws { // 显式指定泛型参数为Void,也可以去掉<Void>,将下方resume改为resume(returning: ()) try await withCheckedThrowingContinuation<Void> { 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) } } } }
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

