Is there an easy way to add Core Data persistence into an already built SwiftUI app?
I've been working through various SwiftUI tutorials to build a very simple reminders/to-do app for myself for the past couple of months. The functionality works, but every time I close the app, I lose the list of tasks. So I started delving into data persistence.
What I found is that Core Data seems to be the preferred method; however, it seems like MOST of the tutorials on Core Data are in conjunction with UIKit. Any Core Data tutorials with SwiftUI usually start with the beginning of the project, creating the models in Core Data from the beginning - not trying to implement them on the backend.
Is there a way to relate my already created "Task" struct to a Core Data model, such that I don't have to recreate everything? With an extension of Task maybe? Or an easy to way to copy my Task struct over to the Core Data model class/entity?
As a beginner, I'm probably approaching this completely wrong, so I'm happy to take a different approach if there's something more preferable.
import Foundation
import SwiftUI
struct Task: Identifiable, Hashable, Codable {
let id: UUID
var taskTitle: String
var taskNotes: String
var isTapped: Bool
init(id:UUID = UUID(), taskTitle:String, taskNotes:String = "", isTapped:Bool = false) {
self.id = id
self.taskTitle = taskTitle
self.taskNotes = taskNotes
self.isTapped = isTapped
}
}
extension Task {
struct Data {
var taskTitle:String = ""
var taskNotes:String = ""
var isTapped:Bool = false
}
var data: Data {
Data(taskTitle: taskTitle, taskNotes: taskNotes, isTapped: isTapped)
}
}
6
1
3.4k