0

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

    }

1 Answer 1

2

Yo may need to separate @publish and @persist properties in two different region. Although composible property wrapper is not supported now, the chain of them still works in most time.

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

            struct PersistInUserDefaults_Wrapper {
              @PersistInUserDefaults(key: "appleID", defaultValue: "") var value
            }

            class AppleUser: ObservableObject {
                static var shared = AppleUser()
                @Published var appleID = PersistInUserDefaults_Wrapper()
            }

            struct ContentMMMMSSSView: View {

                @ObservedObject var appleUser: AppleUser

                var body: some View {

                    return VStack {
                        Text(appleUser.appleID.value)

                    }.onAppear{

                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                            self.appleUser.appleID.value = "Leonard"
                                 }


                        DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
                            self.appleUser.appleID.value = "Bill"
                        }//

                        DispatchQueue.main.asyncAfter(deadline: .now() + 3.5) {
                            self.appleUser.appleID.value  = ""
                                  }

                    }
                }

            }
2
  • This works! Thanks for taking the time to respond. In your opinion, is the ui-non-updates, even with a PassthroughSubject set, a bug, unimplemented functionality, or programmer error? (If a bug, I'll file a report.)
    – Small Talk
    Nov 29, 2019 at 14:58
  • I think we may not get the correct use of the subject now.
    – E.Coms
    Nov 29, 2019 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.