We have now given a very brief tour of what our new Sharing library has to offer. At its core it provides a @Shared
property wrapper that can be used basically anywhere. It can be used in SwiftUI views, in observable models, in UIKit controllers, and more. And it works exactly as you expect. Changes to the state cause the view to update automatically, and if someone updates the state externally then the @Shared
value also immediately updates.
But storing simple values in user defaults is barely even scratching the surface of what the @Shared
property has to offer. There are other persistence strategies provided by the library beyond just .appStorage
, and everything we have learned so far equally applies to those strategies.
The next one we will consider is the .fileStorage
strategy. It allows you to model shared state in your application whose source-of-truth ultimate lies on the file system. It is appropriate to use for more complex pieces of state that can be serialized to bytes because user defaults is really meant for simple data types, such as strings, booleans, integers, and so on.
We are going to make use of this persistence strategy by building a simple feature that we have explored a number of times on Point-Free, most recently when we explored cross-platform Swift. We are going to make it so that we can request a fact about the number our counter is set to, and then make it so that we can save our favorite facts. We would like those facts to be persisted across launches of the app, and so let’s see how that can be accomplished with the @Shared
property wrapper. It may seem like a silly demo to build, but it helps explore the foundational concepts of side effects and persistence without getting bogged down in too many superfluous details.
Let’s dig in.