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

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

问题描述

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

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
  • Double
  • String
  • Bool
  • URL
  • Data
  • Int
  • Double
  • String
  • Bool
  • URL
  • Data

及其可选对等物.您还可以存储符合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

然后我们可以使用保存到它

Then we can save to it using

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的示例.您可能需要为视图创建一个自定义init,以便从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.

尽管您可以编写自己的属性包装器,但该文章

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

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

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