Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize @Published var SwiftUI

Tags:

swift

swiftui

I have the following

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")
    }
}

}

I need to initialize startDay with true, how can I do that? I've tried several ways and it doesn't work, like putting this on top of didSet:

init(){
         startDay = false
      }

Thanks

like image 559
Arturo Avatar asked Nov 19 '25 10:11

Arturo


1 Answers

Here is possible variant

@Published var startDay: Bool

init() {
    startDay = true
    if let storedDay = UserDefaults.standard.value(forKey: "startDay") {
        startDay = storedDay as! Bool
    }
}
like image 128
Asperi Avatar answered Nov 22 '25 03:11

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!