Swift报错求助:‘Type of expression is ambiguous without more context.’ 实例化Identifiable结构体时出错
解决「Type of expression is ambiguous without more context.」错误
这个错误的根源确实是两处类型不匹配——编译器无法推断出你要实例化的DoseModel的正确类型,所以抛出了这个模糊的提示。具体问题和修复方案如下:
问题1:ID类型不匹配
你的DoseModel结构体中id的类型是ObjectIdentifier,但实例化时传入的是UUID()(类型为UUID),两者类型完全不兼容,编译器无法自动转换。
问题2:Units类型不匹配
DoseModel的units属性定义为String类型,但你从JSON中解析的是json["units"].doubleValue(返回Double类型),类型无法对应,进一步加重了编译器的类型推断困惑。
修正后的完整代码
方案1:调整结构体类型匹配传入值(更常用的做法)
把id的类型改成UUID(符合Identifiable协议的常规用法,UUID本身就是Hashable,满足协议要求),同时把解析到的Double类型的units转成String:
func parseJSON(_ dosageData: Data) -> DoseModel? { do { let json = try JSON(data: dosageData) let date = json["date"].stringValue let medicine = json["medicine"].stringValue // 将Double类型的units转换为String let units = String(json["units"].doubleValue) let value = json["value"].stringValue // 现在id类型完全匹配 let dose = DoseModel(id: UUID(), date: date, medicine: medicine, units: units, value: value) return dose } catch { delegate?.didFailWithError(error: error) return nil } } // 模型结构体 struct DoseModel: Identifiable { var id: UUID // 改为UUID类型,符合Identifiable协议常规用法 var date: String var medicine: String var units: String var value: String }
方案2:调整传入值匹配结构体类型
如果你坚持要保留ObjectIdentifier类型的id,可以把UUID()转成ObjectIdentifier,同时把units的Double值转成String:
func parseJSON(_ dosageData: Data) -> DoseModel? { do { let json = try JSON(data: dosageData) let date = json["date"].stringValue let medicine = json["medicine"].stringValue let units = String(json["units"].doubleValue) let value = json["value"].stringValue // 将UUID转为ObjectIdentifier以匹配结构体定义 let dose = DoseModel(id: ObjectIdentifier(UUID()), date: date, medicine: medicine, units: units, value: value) return dose } catch { delegate?.didFailWithError(error: error) return nil } } // 模型结构体保持不变 struct DoseModel: Identifiable { var id: ObjectIdentifier var date: String var medicine: String var units: String var value: String }
一般来说,方案1更符合Swift中Identifiable协议的使用习惯,UUID是生成唯一标识符的标准方式,代码可读性和维护性更好。
内容的提问来源于stack exchange,提问作者AVSoftware
相关产品推荐
相关产品推荐

