迅捷5
如果你想需要保存结构中UserDefault只使用数据格式。
枫结构
struct StudentData:Codable{
var id: Int?
var name: String?
var createdDate: String?
init(from decoder: Decoder) throws {
let values = try? decoder.container(keyedBy: codingKeys.self)
id = try? values?.decodeIfPresent(Int.self, forKey: .id)
name = try? values?.decodeIfPresent(String.self, forKey: .name)
createdDate = try? values?.decodeIfPresent(String.self, forKey: .createdDate)
}
func encode(to encoder: Encoder) throws {
var values = encoder.container(keyedBy: codingKeys.self)
try? values.encodeIfPresent(id, forKey: .id)
try? values.encodeIfPresent(name, forKey: .name)
try? values.encodeIfPresent(createdDate, forKey: .createdDate)
}
}
有两种类型可以转换为数据
- 可编码(可编码和可解码)。
- PropertyListEncoder和PropertyListDecoder
首先,我们使用可编码(可编码和可解码)保存结构
保存值示例
let value = StudentData(id: 1, name: "Abishek", createdDate: "2020-02-11T11:23:02.3332Z")
guard let data = try? JSONEncoder().encode(value) else {
fatalError("unable encode as data")
}
UserDefaults.standard.set(data, forKey: "Top_student_record")
取回值
guard let data = UserDefaults.standard.data(forKey: "Top_student_record") else {
return
}
guard let value = try? JSONDecoder().decode(StudentData.self, from: data) else {
fatalError("unable to decode this data")
}
print(value)
现在我们使用PropertyListEncoder和PropertyListDecoder保存结构
保存值示例
let value = StudentData(id: 1, name: "Abishek", createdDate: "2020-02-11T11:23:02.3332Z")
guard let data = try? PropertyListEncoder().encode(value) else {
fatalError("unable encode as data")
}
UserDefaults.standard.set(data, forKey: "Top_student_record")
取回值
guard let data = UserDefaults.standard.data(forKey: "Top_student_record") else {
return
}
guard let value = try? PropertyListDecoder().decode(StudentData.self, from: data) else {
fatalError("unable to decode this data")
}
print(value)
为了方便起见,可以使用any类型将结构保存在userDefault中。