swift - 使用 Codable 时的错误 - Swift

标签 swift codable encodable

我正在使用 Codable 尝试将 JSON Encode 转换为模型,但出现两个错误。 “KeyedEncodingContainer”类型的值没有成员“encoder”

这是我的代码:

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

最佳答案

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

try container.encode(self.firstName, forKey: .firstName)
try container.encode(self.lastName, forKey: .lastName)

关于swift - 使用 Codable 时的错误 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146862/

相关文章:

json - 使用 swift Codable 解码以值作为键的 JSON

json - 无法通过可编码的swift从json中获取数据

ios - 如何在 Codable 类型中使用 Any

swift - 在 Swift 字典中存储 Encodable

swift - 循环遍历 Swift 结构以获取键和值

ios - Swift:使用 GCDAsyncUdpSocket 接收 UDP

swift - 在 Swift 3.0 中检测 TextView 滚动以显示按钮

swift - 如何在核心数据中使用 swift 4 Codable?

swift - 试图在 Swift 中使一个类可编码,但它的格式不正确?

ios - 箭头 anchor 无法在 swift 中正确显示