我目前在我的應用程式上有很多@State var,我想將它們放在一個結構 Codable 中,這反過來將形成在 API 中作為有效負載發送所必需的 Json 物件。(API 部分超出了這個問題的范圍)。我的“問”是,如何將變數(如下面的 2)放置在可編碼結構內,以便從用戶那里選擇一個值時,這些值將保存在 Json 物件中。
例如,我有 2 個變數:
@State var pregnant: Bool = false
@State var household_size: Int = 1
我將如何將上面的這兩個變數放在可編碼結構中?
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
}
}
現在,當我嘗試將變數的值放入 let = 資格時收到錯誤訊息
let eligibility = Welcome(household: Household(pregnant: pregnant, household_size: household_size))
錯誤:(family_size 也有同樣的錯誤)
不能在屬性初始化器中使用實體成員“懷孕”;屬性初始化程式在“自我”可用之前運行
(Note the eligibility constant above are the values of the @State variable's in the App.)
uj5u.com熱心網友回復:
能夠使用 Class & @Published 而不是 @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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/442250.html
標籤:json swift xcode variables swiftui
上一篇:無法將字串轉換為布林值
