Creating a Synchronized UserDefaults Property Wrapper
Add out-of-sync protection to your wrapper objects.
Since the birth of Swift’s property wrappers, I have seen numerous articles discussing how to create a wrapped variable that can persist itself to the UserDefaults sector. While many of the code examples suffice for the simplest case, I’ve still had some questions gnawing at the back of my head.
- If several of these instances would ever need to be alive at the same time, how will they synchronize?
- How do they synchronize if another process accesses the UserDefaults file, perhaps directly through the file system?
In this article, we look at how to make a property wrapper that persists your variables in UserDefaults. They also stay on top of any value changes, regardless of where they originate.
Analyzing a Simple Implementation
Let’s take a look at a simple implementation of a property wrapper for persisting values in UserDefaults, to get a sense of what it does well and where it fails. We then use these realizations to build a wrapper that handles synchronization like a charm.