使用@AppStorage进行字符串映射

编程入门 行业动态 更新时间:2024-10-19 06:17:52
本文介绍了使用@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的值,例如符合Int或String的枚举.

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进行字符串映射

本文发布于:2023-11-22 06:24:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616313.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   AppStorage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!