我想使用一个密钥将数据保存到UserDefaults。然后我们检查 - 如果输入是'Task'然后在TableViewCell中写入Do;如果'Project'然后让用户移动到另一个TableViewController以查看所有任务。请帮助编码/解码...
protocol UserEntry: Codable {}
struct Task: UserEntry, Codable {
var toDo: String
}
struct Project: UserEntry, Codable {
var name: String
var tasks: [Task]
}
var userEntries: [UserEntry] {
get {
guard let encodedData = UserDefaults.standard.data(forKey: "userEntry"), let decodedData = try? JSONDecoder().decode([UserEntry].self, from: encodedData) else { return [] }
return decodedData
}
set {
guard let encodedData = try? JSONEncoder().encode(newValue) else { return }
UserDefaults.standard.set(encodedData, forKey: "userEntry")
}
}
userEntries.append(Task(toDo: "write a letter"))
userEntries.append(Project(name: "Make a dinner", tasks: [Task(toDo: "buy food"), Task(toDo: "cook food")]))