gui_dos
gui_dos

Reputation: 1211

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

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?

Upvotes: 7

Views: 1211

Answers (2)

gui_dos
gui_dos

Reputation: 1211

It has been solved with today's Xcode 11.5 Swift 5.2.4. Good!

Upvotes: 0

Robert Koval
Robert Koval

Reputation: 546

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

Upvotes: 2

Related Questions