Here's a head-scratcher: implementing a simple wrapper on an ObservableObject property negates SwiftUI updates.
The purpose of the property wrapper is to provide a getter / setter to UserDefaults. The property wrapper works fine. But it stifles SwiftUI updates.
Things I've tried:
-Adding @Published wrapper in addition to my custom wrapper. But Swift at the moment doesn't support composable wrappers (e.g. more than one property wrapper at a time).
-Manually adding a PassthoughSubject publisher, to replicate @Published functionality.
The latter also doesn't fix view updates on property value change.
The only workaround I've found is to abandon property wrappers. I end up having to set state in two places, 1) on the @Published property, and 2) in UserDefaults. This seems clunky, and anti-pattern of duplicating state.
Is this a known-issue?
Full compiling code is at https://github.com/taskcruncher/propertyWrapperSwiftUIBug.git. The 'works' branch is where I've had to duplicate state. The 'broken' branch is below, where using a custom property wrapper breaks SwiftUI updates.
ContentView.swift
import Combine
//https://www.avanderlee.com/swift/property-wrappers/
@propertyWrapper
struct PersistInUserDefaults<T> {
let key: String
let defaultValue: T
var wrappedValue: T {
get {
return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}
set {
UserDefaults.standard.set(newValue, forKey: key)
}
}
}
class AppleUser: ObservableObject {
static var shared = AppleUser()
let subject = PassthroughSubject<String, Never>()
@PersistInUserDefaults(key: "appleID", defaultValue: "") var appleID: String {willSet {
subject.send(newValue) // problem here: does not trigger UI updates
}}
}
struct ContentView: View {
@ObservedObject var appleUser: AppleUser
var body: some View {
return VStack {
Text(appleUser.appleID)
}.onAppear{
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.appleUser.appleID = "Sven"
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
self.appleUser.appleID = "Olaf"
}//update not reflected in UI
DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
self.appleUser.appleID = "Anna"
}//update not reflected in UI
}
}
}
SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView(appleUser: AppleUser.shared)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}