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

Swift 3.2迁移至4.2遇‘无法推断闭包类型’错误求助

解决Swift 4.2中Unable to infer closure type in the current context错误

这个问题是Swift 4.2对泛型类型推断的严格性提升导致的——编译器没办法自动从你的闭包返回值推断出RequestDataProvider的两个泛型关联类型(Representation和Request)。下面是两种可行的修复方案:

方案1:显式指定泛型参数

直接在初始化RequestDataProvider时明确写出它的泛型类型,给编译器清晰的类型信息:

private func presentIndustrySearch() { 
    // 明确指定泛型参数为Industry和IndustriesRequest
    let dataProvider = RequestDataProvider<Industry, IndustriesRequest> { 
        return IndustriesRequest() 
    }
}

方案2:让闭包返回类型更明确

如果不想写全泛型参数,也可以在闭包中显式标注返回类型,帮助编译器完成推断:

private func presentIndustrySearch() { 
    let dataProvider = RequestDataProvider { () -> IndustriesRequest in
        return IndustriesRequest() 
    }
}

为什么原来的写法在Swift 3.2中可行?

Swift 3.2的类型推断规则相对宽松,编译器可以通过闭包内的返回值反向推断泛型类型。但Swift 4.2收紧了这部分规则,对于泛型初始化器的闭包参数,需要更明确的类型提示才能完成推断。

从你给出的代码来看,IndustriesRequest的Parser关联类型已经正确关联到[Industry],所以只要补上类型提示就能解决这个推断问题。

内容的提问来源于stack exchange,提问作者Akshay Crasta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:53:32