ios - 如何在 UserDefaults swift 中设置枚举数组
问题描述
我有自定义类型的枚举数组,我想使用 swift4 将它存储在 UserDefaults 中。
enum DataType : Int
{
case cloud = 1, files = 2, googleDrive = 3, mega = 4, others = 5
}
//
let arrayOfData : [DataType] = [.cloud, .files, .mega]
我想将此数组存储在 UserDefaults 中。
解决方案
使DataType
符合Codable
. 这很简单,只需添加Codable
enum DataType : Int, Codable
{
case cloud = 1, files, googleDrive, mega, others // the consecutive raw values are inferred
}
let arrayOfData : [DataType] = [.cloud, .files, .mega]
现在将数组编码为 JSON 数据并保存
let data = try! JSONEncoder().encode(arrayOfData)
UserDefaults.standard.set(data, forKey: "dataType")
并相应地读回来
do {
if let data = UserDefaults.standard.data(forKey: "dataType") {
let array = try JSONDecoder().decode([DataType].self, from: data)
}
} catch { print(error)}
推荐阅读
- oracle - ORA-01292: 使用在线目录时无法使用日志挖掘器访问日志文件
- jenkins-groovy - 作业 DSL 脚本参考
- pandas - pd DataFrame,需要加列,一次性将文本字符串date_time解析成pandas year、dayOfWeek等
- html - 在纯 CSS 中创建第二个边框
- javascript - 该表达式不计算为函数,因此在使用 auth.currentUser 时无法调用它
- javascript - 在单元测试期间抑制控制台日志中的反应错误
- docker - 如何从 Docker-Composed C# 应用程序连接到本地 SQL Server Express 数据库?
- javascript - Nextjs 路由 - 捕获除公用文件夹之外的所有内容
- javascript - 单击按钮子元素时错误的 event.target
- rest - Cosmos DB REST API 授权标头不允许我替换文档