Antonio Labra
Antonio Labra

Reputation: 2020

Error while I'm trying to decode using CodingKeys

This my struct

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

Coding Keys

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

}

init

init(userNotificationId: Int){

        self.userNotificationId = userNotificationId
    }

Decoder

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

Encoder

init(from encoder: Encoder) throws{


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

I get the following error inside the coding method

'self' used before all stored properties are initialized

Upvotes: 0

Views: 463

Answers (1)

Gereon
Gereon

Reputation: 17882

What is init(from encoder: Encoder) supposed to be? You're not conforming to Encodable, and if you were, you would need to implement func encode(to encoder: Encoder) throws, not another initializer.

That said, your explicit implementation of init(from decoder: Decoder) throws does nothing different from what the compiler would synthesize for you, so it's better to remove it entirely as well.

struct Settings: Hashable, Decodable {
    let id = UUID()
    let userNotificationId: Int

    private enum CodingKeys: String, CodingKey{
        case userNotificationId = "usuarioNotificacionMovilId"
    }

    init(userNotificationId: Int) {
        self.userNotificationId = userNotificationId
    }
}

is probably all you need.

Upvotes: 0

Related Questions