AppStorage
is a wrapper of UserDefaults which provides a quick way to store simple values.
Sometimes, we want to store more complex value like a struct in AppStorage
though
struct Configuration {
let name: String
let baseURL: String
}
I have found 2 fantastic tutorials to help me with this:
But when I implement the code following the above tutorials, my app crashes.
More researching has pointed me to this StackOverflow answer
You are running into infinite recursion. This is because types that conforms to both Encodable and RawRepresentable automatically get this encode(to:) implementation (source), which encodes the raw value. This means that when you call JSONEncoder().encode, it would try to call the getter of rawValue, which calls JSONEncoder().encode, forming infinite recursion.
Adding the encode(to:)
and init(from:)
to my type has helped fixing the crash.