Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 13.4: didSet() not called anymore for a @Published Bool when using toggle()

Tags:

swiftui

Until iOS 13.4 I was using a property observer to update the UserDefaults for a @Published Bool value

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

With the first beta of iOS 13.4 didSet() is not called anymore if I use in SwiftUI the toggle() method and I must use a logical negation:

Button(action: {  
    // self.settings.mutedAudio.toggle()  doesn't work in iOS 13.4  
    self.settings.mutedAudio = !self.settings.mutedAudio // workaround  
}) {  
    Image(systemName: settings.mutedAudio ? "speaker.slash.fill" : "speaker.2.fill").resizable().frame(width: 24, height: 24)  
}

Is there a better solution than waiting for the next iOS 13.4 beta?

like image 777
gui_dos Avatar asked Feb 08 '20 19:02

gui_dos


1 Answers

You can directly subscribe to mutedAudio in your init or another place, for example:

class SomeClass: ObservableObject {
    var cancellable: Cancellable?

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

    init() {
        cancelable = $mutedAudio.sink(receiveValue: { (value) in
            UserDefaults.standard.set(value, forKey: "mutedAudio")
        })
    }
}
like image 134
Robert Koval Avatar answered Oct 13 '22 01:10

Robert Koval