在iOS 13.4之前,我一直使用属性观察器为@Published Bool值更新UserDefaults。

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

在iOS 13.4的第一个beta中,如果我在SwiftUI中使用toggle()方法,就不再调用didSet(),并且必须使用逻辑取反:
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)
}

是否有比等待下一个iOS 13.4 Beta更好的解决方案?

最佳答案

您可以在您的init或其他位置直接订阅mutedAudio,例如:

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

10-08 16:07