Home > Mobile >  Connect @State variables to a Codable struct
Connect @State variables to a Codable struct

Time:03-10

I currently have lots of @State var's on my app that I'd like to place inside a struct Codable which in turn will form the Json Object necessary to send as payload in an API. (The API part is out of scope for this question). My 'ask' is, how do I place variables like the 2 I have below, inside the codable struct so when selected a value from the user, those values will be saved in a Json object.

For example, I have 2 variables:

@State var pregnant: Bool = false
@State var household_size: Int = 1

How will I place these two variables above in the codable struct?

struct Welcome: Codable {
        let household: Household
    }

    struct Household: Codable {
        var pregnant: String
        var household_size: Int

        enum CodingKeys: String, CodingKey {
            case pregnant
            case household_size
    }
}

Right now, I'm receiving an error when I try to place the values of the variables into let = eligibility

let eligibility = Welcome(household: Household(pregnant:  pregnant, household_size: household_size))

Error: (same error for household_size too)

Cannot use instance member 'pregnant' within property initializer; property initializers run before 'self' is available

(Note the eligibility constant above are the values of the @State variable's in the App.)

CodePudding user response:

Was able to successfully di this using Class & @Published instead of @State.

class User: ObservableObject, Codable {
    enum CodingKeys: CodingKey {
        case disabled
    }

    init() { }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        disabled = try container.decode(Bool.self, forKey: .disabled)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(disabled, forKey: .disabled)
    }

    @Published var disabled: Bool = false

}
  • Related