使用@AppStorage 进行字符串映射 [英] Using @AppStorage for string map

查看:22
本文介绍了使用@AppStorage 进行字符串映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 @AppStorage 用于 SwiftUI 应用程序中的字符串映射?

How can I use @AppStorage for a string map in a SwiftUI app?

这就是我想要做的:

@AppStorage("ratings") var ratings: [String: Double] = []

但这给了我错误消息调用初始化程序时没有完全匹配".查看文档时,似乎只支持几种数据类型.是否可以将其编码为 Data?

But this gives me the error message "No exact matches in call to initializer". When looking at the documentation, it looks like only a few data types are supported. It is possible to encode it as Data?

推荐答案

查看文档 对于 @AppStorage,您当前可以使用此属性包装器存储的唯一值是

Looking at the documentation for @AppStorage the only values that you can currently store using this property wrapper are

  • Int
  • 双人
  • 字符串
  • 布尔
  • 网址
  • 数据

以及它们的可选对应项.您还可以存储符合 RawRepresentable 的值,例如符合 IntString 的枚举.

And their optional counterparts. You can also store values that conform to RawRepresentable, like enums that conform to Int or String.

如果您想使用此方法存储字典,则必须将其转换为数据并以这种方式存储.

If you want to store a dictionary using this method then you would have to convert it to data and store it that way.

@AppStorage("ratings")
var ratings: Data = Data() // we need to initialize it with something

然后我们可以使用

let data = ["Hello": 5.0]
guard let ratings = try? JSONEncoder().encode(data) else { return }
self.ratings = ratings

如果我们想检索它,我们可以执行以下操作:

And if we want to retrieve it we can do the following:

guard let decodedRatings = try? JSONDecoder().decode([String:Double].self, from: ratings) else { return }
print(decodedRatings)

否则你将不得不直接使用 UserDefaults,你总是可以使用 onChange 和 State 来管理它.请参阅此 示例 如何使用 onChange.您可能需要为您的视图创建自定义初始化,以便从 UserDefaults 填充 State 值.

Otherwise you will have to use UserDefaults directly, you can always use onChange and State to manage it. See this example of how to use onChange. You may need to create a custom init for your view so as to populate the State the value from UserDefaults.

虽然您可以编写自己的属性包装器,但这篇文章作者:John Sundell 详细解释了如何做到这一点.

Though you could write your own property wrapper, this article by John Sundell explains in detail how to do it.

这篇关于使用@AppStorage 进行字符串映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆