1

我正在Codable尝试将EncodeJSON 转换为模型,但出现两个错误。 “KeyedEncodingContainer”类型的值没有成员“编码器”

这是我的代码:

import UIKit

struct NewCustomer : Codable {

    var firstName :String
    var lastName :String


    private enum CodingKeys : String, CodingKey {
        case firstName
        case lastName
    }

    func encode(to encoder :Encoder) throws {

        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encoder(self.firstName, forKey: .firstName)  // error here
        try container.encoder(self.lastName, forKey: .lastName)  // error here
    }
}

let customer = NewCustomer(firstName: "Jake", lastName: "Reynolds")

let encodedCustomerJSON = try! 
JSONEncoder().encode(customer)

print(encodedCustomerJSON)

print(String(data: encodedCustomerJSON, encoding: .utf8)!)
4

2 回答 2

2

在给出错误的两行更改encoderencode。请注意,上面的行(即 var container...)将保留encoder.

try container.encode(self.firstName, forKey: .firstName)
try container.encode(self.lastName, forKey: .lastName)
于 2019-03-13T16:32:48.503 回答
0

如前所述,这是一个错字encodevs. encoder

try container.encode(...

实际上,在这种情况下,您根本不需要指定CodingKeys编码方法,这就足够了:

struct NewCustomer : Codable {
    var firstName, lastName : String
}
于 2019-03-13T16:39:51.410 回答