Below, I have a codable class that I'm able to connect Published variables with the purpose of converting them to Json and sending an API (API is out of scope). I have these two variables connected in the app to a toggle and picker which I can print out the values print(user.age) etc..
when a button is pressed but.. now, I'd like a way to save this data in json format so I can print out both var's in json format (pretty printed) in the console when the button is pressed. Thanks!
class User: ObservableObject, Codable {
enum CodingKeys: CodingKey {
case disabled
case age
}
init() { }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
disabled = try container.decode(Bool.self, forKey: .disabled)
age = try container.decode(Int.self, forKey: .age)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(disabled, forKey: .disabled)
try container.encode(age, forKey: age)
}
@Published var disabled: Bool = false
@Publisehd var age: Int = 18
}
@StateObject var user = User() // Connects to the Class.