使用Himotoki解码Swift结构体时遇泛型参数推断错误
解决Himotoki中
Generic parameter 'T' could not be inferred错误 这个错误我之前也碰到过,本质是Swift编译器没法自动推断出<|-|?操作符对应的泛型类型,咱们来一步步解决它:
首先回顾你的代码场景:
struct NextItem { let question: String? let condition: [String : [String]]? } extension NextItem: Decodable { static func decode(_ e: Extractor) throws -> NextItem { return try NextItem( question: e <|? "question", condition: e <|-|? "condition" ) } }
错误原因
Himotoki的<|-|?是用于解码可选字典类型的泛型操作符,当字典的值是数组([String])这种嵌套复杂类型时,Swift编译器无法自动推断出泛型参数T的具体类型,因此抛出了Generic parameter 'T' could not be inferred错误。
解决方案
方案1:显式指定类型
在<|-|?操作符后面加上类型标注,明确告诉编译器要解码的目标类型:
extension NextItem: Decodable { static func decode(_ e: Extractor) throws -> NextItem { return try NextItem( question: e <|? "question", condition: e <|-|? "condition" as [String : [String]]? ) } }
方案2:使用decodeIfPresent显式解码
如果觉得类型标注不够直观,也可以直接调用decodeIfPresent方法,显式指定数组类型的解码器:
extension NextItem: Decodable { static func decode(_ e: Extractor) throws -> NextItem { return try NextItem( question: e <|? "question", condition: try e.decodeIfPresent("condition", decoder: decode) ) } }
这里的decode是Himotoki为[String]提供的默认解码器,编译器能清晰推断出整个字典的类型。
两种方案都能让编译器正确识别解码类型,解决这个推断错误。
内容的提问来源于stack exchange,提问作者user3239711
相关产品推荐
相关产品推荐

