通过使用下面的代码,我可以成功地将由“struct”组成的数组(即 [structData])保存到 userDefautls。
// save [dataCell] encoded to JSON
func save(_ cellDatas: [cellData]){
let encoDatas = cellDatas.map{ try? JSONEncoder().encode($0)}
UserDefaults.standard.set(encoDatas, forKey: "datas")
}
// decode JSON array to [cellData]
func load() -> [cellData]{
guard let encodedData = UserDefaults.standard.array(forKey: "datas") as? [Data] else {
return []
}
return encodedData.map{try! JSONDecoder().decode(cellData.self, from: $0)}
}
// retrieve datas from UD
func retrieveData() -> [cellData]{
datas = UserDefaults.standard.array(forKey: "datas") == nil ? initialData : load()
return datas
}
但是,现在我需要保存一个二维数组 [[structData]],因此我尝试了这些代码,替换了一些代码。但没有成功。
// save [dataCell] encoded to JSON
func saveTableList(_ tableList: [[cellData]]){
let encoDatas = tableList.map{ try? JSONEncoder().encode($0)}
UserDefaults.standard.set(encoDatas, forKey: "tableList")
}
// decode JSON array to [cellData]
func loadTableList() -> [[cellData]]{
guard let encodedData = UserDefaults.standard.array(forKey: "tableList") as? [[Data]] else {
return []
}
return encodedData.map{try! JSONDecoder().decode(cellData.self, from: $0)}
// this $0 has the error that "Cannot convert value of type '[Data]' to expected argument type 'Data'"
//so I tryied this way instead.
// return encodedData.map{try! JSONDecoder().decode(cellData.self, from: encodedData)}
//but it didn't work properly
}
// retrieve datas from UD
func retrieveTableListData() -> [cellData]{
datas = UserDefaults.standard.array(forKey: "datas") == nil ? initialData : load()
return datas
}
如何将 [[struct]] 的二维数组编码/解码为 JSON 并使用 userDefautls 保存/加载它?
最佳答案
为什么不立即对整个二维数组进行编码,而不是创建编码对象的数组。我尝试了这个并且成功了。
func saveTableList(_ tableList: [[cellData]]) {
guard let encodedCellData = try? JSONEncoder().encode(tableList) else {
print("Error")
return
}
UserDefaults.standard.set(encodedCellData, forKey: "tableList")
}
func loadTableList() -> [[cellData]] {
guard let encodedCellData = UserDefaults.standard.value(forKey: "tableList") as? Data,
let cellData = try? JSONDecoder().decode([[cellData]].self, from: encodedCellData) else {
return []
}
return cellData
}
关于arrays - Swift4.2 如何将 "struct"构造的二维数组保存到UserDefaults中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55065003/