【问题标题】:Error while I'm trying to decode using CodingKeys尝试使用 CodingKeys 解码时出错
【发布时间】:2020-05-15 18:14:35
【问题描述】:

这是我的结构

import Foundation
struct Settings: Hashable, Decodable{
    var Id = UUID()
    var userNotificationId : Int
}

编码键

    private enum CodingKeys: String, CodingKey{
        **case userNotificationId = "usuarioNotificacionMovilId"** (this is the line that gets me errors)

}

初始化

init(userNotificationId: Int){

        self.userNotificationId = userNotificationId
    }

解码器

 init(from decoder: Decoder) throws{
        let container = try decoder.container(keyedBy: CodingKeys.self)
        userNotificationId = try container.decodeIfPresent(Int.self, forKey: .userNotificationId) ?? 0
}

编码器

init(from encoder: Encoder) throws{


  var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(userNotificationId, forKey: .userNotificationId)
}

我在编码方法中收到以下错误

在所有存储属性初始化之前使用'self'

【问题讨论】:

    标签: swift codable


    【解决方案1】:

    init(from encoder: Encoder) 应该是什么?你不符合Encodable,如果是,你需要实现func encode(to encoder: Encoder) throws,而不是另一个初始化器。

    也就是说,您对 init(from decoder: Decoder) throws 的显式实现与编译器将为您合成的内容没有什么不同,因此最好也将其完全删除。

    struct Settings: Hashable, Decodable {
        let id = UUID()
        let userNotificationId: Int
    
        private enum CodingKeys: String, CodingKey{
            case userNotificationId = "usuarioNotificacionMovilId"
        }
    
        init(userNotificationId: Int) {
            self.userNotificationId = userNotificationId
        }
    }
    

    可能就是你所需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2019-12-07
      • 2014-04-19
      相关资源
      最近更新 更多