We have accomplished quite a bit in this series so far. We now have 2 primary methods of sharing state in a Composable Architecture application:
We can use a simple, unadorned
@Shared
property wrapper to represent a piece of state that is passed in from the parent feature, and shares its state with the parent.
Or we can provide a persistence strategy to the
@Shared
property wrapper that describes how we want the state to be persisted to an outside system. This makes it possible to globally share the state with any part of the application without needing to explicitly pass it around, and even persist the data to some external storage. Currently we have two persistence strategies:We have an in-memory persistence strategy that just doesn’t persist data at all. This means you will lose the data when the app re-launches, but that can be fine for many use cases.
And we have a user defaults persistence strategy that saves simple data types to user defaults. We even went the extra mile to observe changes to user defaults so that if someone makes a change outside of the
@Shared
property wrapper we can be sure to update our state.
This is all great, but user defaults persistence is a bit limited. It only works for the most basic of data types, such as booleans, integers and strings, and therefore is appropriate for little scraps of data and user preferences.
There are many times that we need to persist far more significant chunks of data, and the easiest place to do that is directly on the device’s file system. And the easiest way to serialize the data to disk is via Swift’s Codable
protocol and JSON serialization.
Let’s see what it takes to introduce a 3rd conformance to the PersistenceKey
protocol and make file storage a reality in Composable Architecture features.