此代码世界的新功能,并提前感谢,
我收到错误
无法指定'String'类型的值?输入'ModalA.ModalC?'
这是我的模型类,
struct ModalA: Codable {
struct ModalB: Codable {
let value2: String?
let value3: ModalC?
private enum CodingKeys: String, CodingKey {
case value3 = "Any"
case value2 = "Anything"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
value2 = try values.decodeIfPresent(String.self, forKey: .value2)
value3 = try values.decodeIfPresent(String.self, forKey: .value3) // getting error on this line
}
}
struct ModalC: Codable {
let value3: String?
}
let value1: ModalB?
}
如何解决此错误?
答案 0 :(得分:0)
您的value3
属性类型为ModalC
,但在解码时,您尝试解析String
值(将String.self
传递给decodeIfPresent
方法时)。
decodeIfPresent
方法将可解码值的类型作为第一个参数。在您的情况下,decodeIfPresent
方法返回String
值,并且您尝试将String
值设置为ModalC
类型的属性。
因此,为了解决错误,您应该说要为密钥ModalC
获取.value3
类型的值。为此,您应该像ModalC.self
那样传递:
value3 = try values.decodeIfPresent(ModalC.self, forKey: .value3)
答案 1 :(得分:0)
您可以通过
解决此问题value3 = try values.decodeIfPresent(ModalC.self, forKey: .value3)
但将value3声明为可选
let value3: ModalC?
如果它在解析的json中最初存在,将获取它,因此?
就足够了
答案 2 :(得分:0)
您应该使用
auto answer = star_database.find(pN1); // lookup the proper name in the database
if (answer == star_database.end()) // did we find it?
{
cout << "No star with the proper name "<< pN1 <<" was found"<< endl;
}
else
{
cout << "Star : "<< "proper name: "<< pN1 <<
" distance: "<< answer->second.distance << " light years" <<
" HD num: "<< answer->second.hdN <<
" HR num: "<< answer->second.hrN <<
" common name: "<< answer->second.name << endl;
}
您可以阅读我的帖子here了解更多信息。