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 中。
使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)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           863 次  |  
        
|   最近记录:  |