🎉 End-of-year Sale! Save 25% when you subscribe today.

Tour of Sharing: File Storage: Part 1

Episode #307 • Dec 16, 2024 • Subscriber-Only

@Shared is far more than a glorified version of @AppStorage: it can be customized with additional persistence strategies, including the file storage strategy that comes with the library, which persists far more complex data than user defaults. We will create a complex, new feature that is powered by the file system.

Collection
Tour of Swift Sharing
Tour of Sharing: File Storage: Part 1
Locked

Unlock This Episode

Our Free plan includes 1 subscriber-only episode of your choice, plus weekly updates from our newsletter.

Sign in with GitHub

Introduction

Brandon

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.

Stephen

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.

Using fileStorage


References

Downloads

Sample code

Get started with our free plan

Our free plan includes 1 subscriber-only episode of your choice, access to 64 free episodes with transcripts and code samples, and weekly updates from our newsletter.

View plans and pricing