You need to enable JavaScript to run this app. Swift中如何对Result类型使用flatMap解决表达式类型歧义报错
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何对Result类型使用flatMap解决表达式类型歧义报错

报错原因

endpoint.decode 是会抛出任意Error类型的转换函数,而你要得到的Result<Response, AFError>要求错误类型必须为AFError,flatMap要求转换前后的错误类型完全一致,编译器无法自动推导类型,就抛出了「Type of expression is ambiguous without more context」的错误。

解决方案

方案1:补全你写的闭包逻辑

在闭包内手动捕获解码异常,将错误统一转换为AFError类型即可:

let result = response.result.flatMap { (data) -> Result<Response, AFError> in
    do {
        let decodedResponse = try endpoint.decode(data)
        return .success(decodedResponse)
    } catch let decodeErr {
        return .failure(AFError.responseSerializationFailed(reason: .customSerializationFailed(error: decodeErr)))
    }
}

方案2:使用tryMap简化代码

Swift内置的tryMap方法专门适配会抛出异常的转换逻辑,代码更简洁:

let result: Result<Response, AFError> = response.result
    .tryMap(endpoint.decode)
    .mapError { error in
        error as? AFError ?? AFError.responseSerializationFailed(reason: .customSerializationFailed(error: error))
    }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 04:27:04