如何在类中使用 @AppStorage

huangapple go评论50阅读模式
英文:

How to use @AppStorage with a class

问题

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?

英文:

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?

答案1

得分: -1

错误可能有点晦涩,但在这种情况下,它的真正含义是类似于:

此类型不被AppStorage允许。

AppStorage不允许存储除基本数据类型之外的任何内容。但有方法可以绕过这个限制。

  1. 因此,不要尝试存储整个 TestClass,我建议只存储该类内部的实际字段。如果你考虑一下,这也是你唯一需要的东西,通过它,你可以无缝地重新创建你的状态。无需存储其他任何东西。
  2. 我认为这也是你尝试的方法,当将类设为 codable 时。你可以序列化该类,将其存储为字符串,然后与AppStorage一起存储,并在需要时反序列化它。此帖子的答案描述得相当好。
英文:

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.

huangapple
  • 本文由 发表于 2023年5月7日 03:46:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定