Store a codable model into AppStorage

March 17, 20241 min read#swift, #swiftui, #indie

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.

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist

© An Tran - 2024