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
let eligibility = Welcome(household: Household(pregnant: pregnant, household_size: household_size))
(Note the eligibility constant above are the values of the @State variable's in the App.)
Thank you!
I was able to do this with @Published.
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
}