0

I'm new to Swift development and I'm having trouble trying to save a class to @AppStorage. If I have the following simple class:

class TestClass : Codable {
    var testBool: Bool = true
}

And in the view:

struct ContentView: View {
    var testClass1: TestClass = TestClass()
    @AppStorage("testClass2") var testClass2: TestClass = TestClass()
}

The first var compiles fine but the @AppStorage var gives the error "No exact matches in call to initializer"

Does anyone know what I need to add to get this to compile?

HangarRash
  • 7,314
  • 5
  • 5
  • 32

1 Answers1

-1

The error might be a bit cryptic but what it really means in this case is something like:

This type is not allowed by Appstorage.

AppStorage does not allow for anything other than basic data types to be stored. But there are ways around that.

  1. So instead of trying to store your entire TestClass, I would suggest storing only the actual fields inside of that class. If you think about it this is also the only thing you need, out of this you can recreate your state seamlessly. No need to store anything else.
  2. I think that is also what you tried, when making the class codable. You could serialize the class, store it in a String, which then is stored with AppStorage and deserialize it when needed. The answer of this post describes it pretty well.
Throvn
  • 795
  • 7
  • 19
  • If the answer is in another SO question you should mark it as a duplicate. – lorem ipsum May 06 '23 at 21:19
  • The answer in the link you provided is almost exactly what I want except they store an Array of the class and I want to just store a single class. I guess I can just create an array with one class contained inside. – HalifaxNick May 06 '23 at 22:45