我正在Codable
尝试将Encode
JSON 转换为模型,但出现两个错误。
“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)!)