当你有模型时,如何在codable中使用init方法?

时间:2018-05-28 19:07:56

标签: ios swift4 codable decodable swift4.1

此代码世界的新功能,并提前感谢,

我收到错误

  

无法指定'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?
}

如何解决此错误?

3 个答案:

答案 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了解更多信息。