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
相关产品推荐
相关产品推荐

