You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:45:02