首页 > 解决方案 > 如何在 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 中。

标签: iosarraysswiftenums

解决方案


使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)}

推荐阅读