-1

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

  • change `let` to `var` – lorem ipsum Mar 07 '22 at 21:28
  • What is the error message that you get? – Sweeper Mar 07 '22 at 21:30
  • @Sweeper, Thanks - just edited the question w/ the error message. – William Zebrowski Mar 07 '22 at 21:39
  • @WilliamZebrowski you need to show the context that your `let eligibility` line is in, but my guess is you're trying to define it at the top level of a `struct` or `class`, which isn't valid, since it relies on other properties. You may want to look at https://stackoverflow.com/questions/56691630/swiftui-state-var-initialization-issue – jnpdx Mar 07 '22 at 22:09
  • Since the user can edit the values in the UI you should have some kind of Save button and then create an instance of Welcome (change that to a better name) in the action of that button containing all the current values of your State variables – Joakim Danielson Mar 08 '22 at 06:33
  • can you produce a [Minimal, Reproducible Example (MRE)](https://stackoverflow.com/help/minimal-reproducible-example) ? – meomeomeo Mar 08 '22 at 07:44

1 Answers1

0

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

}