Search code examples
swiftcodableencodable

Errors when using Codable - Swift


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)!)

Solution

  • 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)