Reputation:
I am using Codable
to try to Encode
JSON to a Model but I get two errors.
Value of type 'KeyedEncodingContainer' has no member 'encoder'
Here's my code:
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)!)
Upvotes: 1
Views: 77
Reputation: 285064
As already mentioned it's a typo encode
vs. encoder
:
try container.encode(...
Practically you don't need to specify CodingKeys
and the encoding method at all in this case, this is sufficient:
struct NewCustomer : Codable {
var firstName, lastName : String
}
Upvotes: 0
Reputation:
Change encoder
to encode
on the two lines giving errors. Please note that the line above (i.e. var container...) will keep encoder
.
try container.encode(self.firstName, forKey: .firstName)
try container.encode(self.lastName, forKey: .lastName)
Upvotes: 2