如何在 UserDefaults swift 中设置枚举数组

Boo*_*ppu 1 arrays enums ios swift

我有自定义类型的枚举数组,我想使用 swift4 将它存储在 UserDefaults 中。

enum DataType : Int
{
   case cloud = 1, files = 2, googleDrive = 3, mega = 4, others = 5
}
//
let arrayOfData : [DataType] = [.cloud, .files, .mega]
Run Code Online (Sandbox Code Playgroud)

我想将此数组存储在 UserDefaults 中。

vad*_*ian 7

使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]
Run Code Online (Sandbox Code Playgroud)

现在将数组编码为 JSON 数据并保存

let data = try! JSONEncoder().encode(arrayOfData)
UserDefaults.standard.set(data, forKey: "dataType")
Run Code Online (Sandbox Code Playgroud)

并相应地读回来

do {
    if let data = UserDefaults.standard.data(forKey: "dataType") {
        let array = try JSONDecoder().decode([DataType].self, from: data)
    }
} catch { print(error)}
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,JSON 是更好的选择,因为它没有像 plist 标头和标签那样的开销。UserDefaults 中的属性列表仅在对象包含 JSON 不支持的类型(日期和数据)时才有用。 (2认同)