当我试图使用CodingKeys解码时出错。

问题描述 投票:0回答:1

这是我的结构

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个回答
0
投票

什么是 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
    }
}

可能是你所需要的全部。

© www.soinside.com 2019 - 2024. All rights reserved.