We ended last year by giving a tour of our new open source library called “Sharing”. It’s an extremely powerful library that allows you to instantly share state with multiple parts of an application, and persist it to external systems, such as user defaults, file storage, and more. And we showed how the library is compatible with SwiftUI views, observable models, UIKit view controllers, and there are even more places the library can be used that we haven’t shown yet.
But that tour barely scratched the surface of what the library is capable of. We only showed off the persistence strategies that come with the library, which are the appStorage
, fileStorage
and inMemory
strategies. They are handy, but the real power of the library comes when defining your own custom persistence strategies.
We designed the library so that anybody can create their own persistence strategies that load data from and save data to external storage systems, and with a bit of extra work, one can even make sure that if the external source of data changes, the @Shared
value will also automatically update. You can even make it so that your custom persistence strategy is easy to use in previews and tests.
The most obvious example of a custom persistence strategy would be a SQLite-backed strategy. What if you could hold state in your features that was secretly being persisted to a database on disk? And what if anytime the database updated your views immediately re-rendered?
It turns out it’s quite easy to accomplish this, and it’s amazing to see. But we’re going to start by showing why one might want to move away from the file storage strategy that comes with the library and towards a custom SQL-based persistence strategy.
Let’s take a look.