swift - 在 UserDefault 问题中保存自定义字典
问题描述
如何在 UserDefault 中保存自定义字典,我尝试通过 PropertyListEncoder,但出现错误。
struct pointDict {
let id: Int
let name: String
let type: Int8
}
var pointsPlane: [pointDict] = []
...
UserDefaults.standard.set(try? PropertyListEncoder().encode(pointsPlane), forKey:"pointsPlane")
Class 'PropertyListEncoder' requires that 'ViewControllerPlane.pointDict' conform to 'Encodable'
解决方案
错误表明您必须pointDict
遵守Encodable
. 所以就这样做吧。
struct PointDict: Encodable { // also make struct model name's first letter uppercased.
let id: Int
let name: String
let type: Int8
}
另外,不要使用try?
、使用do try catch
和处理抛出的错误。
do {
UserDefaults.standard.set(try PropertyListEncoder().encode(pointsPlane), forKey:"pointsPlane")
} catch { print(error) }
推荐阅读
- android - IntelliJ 中的任务“:app:compileDebugJavaWithJavac”执行失败
- linux - Pyscreenshot 循环滞后显示
- ruby-on-rails - Rails:模态表单提交后页面处于空闲状态且不可点击
- sql - 查找字符串中数字的出现
- javascript - LZ-string压缩文本的Mysql数据类型
- javascript - 如何从内容脚本中调用注入的 javascript 函数
- java - JavaFX 相对于父级调整子级的大小
- xpath - 不支持元素
- python - Django 提出表单 ValidationError 不起作用
- php - 我的 SQL 查询不会正确输出字段结果