初始化@Published var SwiftUI

时间:2020-04-20 02:38:53

标签: swift swiftui

我有以下

import Foundation


class TimeToEatTrackerViewModel: ObservableObject {

@Published var currentMeal: Int = UserDefaults.standard.integer(forKey: "CurrentMeal") {
    didSet {
        UserDefaults.standard.set(self.currentMeal, forKey: "CurrentMeal")
    }
}

@Published var startDay: Bool = UserDefaults.standard.bool(forKey: "startDay") {

    didSet {
        UserDefaults.standard.set(self.startDay, forKey: "startDay")
    }
}

}

我需要用startDay初始化true,我该怎么做?我已经尝试了几种方法,但都行不通,例如将其放在didSet之上:

init(){
         startDay = false
      }

谢谢

2 个答案:

答案 0 :(得分:1)

这是可能的变体

@Published var startDay: Bool

init() {
    startDay = true
    if let storedDay = UserDefaults.standard.value(forKey: "startDay") {
        startDay = storedDay as! Bool
    }
}

答案 1 :(得分:-1)

在这里不清楚您要问什么。 如果您希望在运行应用程序时始终将startDay初始化为true,则:

@Published var startDay: Bool = true {
    didSet {
        UserDefaults.standard.set(self.startDay, forKey: "startDay")
    }
}