//// ContentView.swift// Data Practice//// Created by Eusebio Taba on 3/24/24.//import SwiftUIimport SwiftDatastruct ContentView:View {@Environment(\.modelContext)privatevar modelContext//"bridge to SwiftData"// PRIVATE means this will only works in this particular view@Queryprivatevar todoplural: [Todo_Class]var body: some View {NavigationSplitView{List{ForEach(todoplural){ iterateArrayOfTodos inNavigationLink{Text("How are you?")}label:{// Text(todo)Text(iterateArrayOfTodos.titulito)}} .onDelete(perform: deleteItems)}//end List .toolbar{ToolbarItem(placement: .navigationBarTrailing){EditButton()}ToolbarItem{Button(action: addItem){Label("Add Item", systemImage:"plus")//PLUS SIGN - read loud for blind people}}}}detail:{Text("Select an item")}}privatefuncaddItem(){withAnimation{// let newItem = Item(timestamp: Date())//create a new object, instantiate class Todolet newToBeShownInDisplay =Todo_Class(titulito:"Hello Mommy")// modelContext.insert(newItem)// saving into SwiftData modelContext.insert(newToBeShownInDisplay)}}privatefuncdeleteItems(offsets: IndexSet){withAnimation{for index in offsets { modelContext.delete(todoplural[index])}}}}#Preview{ContentView() .modelContainer(for: Todo_Class.self, inMemory:true)}
Data_PracticeApp file
//// Data_PracticeApp.swift// Data Practice//// Created by Eusebio Taba on 3/24/24.//import SwiftUIimport SwiftData@mainstruct Data_PracticeApp:App {var sharedModelContainer: ModelContainer ={let schema =Schema([ Item.self,//here you start adding new classes Todo_Class.self, ])let modelConfiguration =ModelConfiguration(schema: schema, isStoredInMemoryOnly:false)do {returntryModelContainer(for: schema, configurations: [modelConfiguration])}catch{fatalError("Could not create ModelContainer: \(error)")}}()var body: some Scene {WindowGroup{ContentView()} .modelContainer(sharedModelContainer)}}
Item file
//// Item.swift// Data Practice//// Created by Eusebio Taba on 3/24/24.//import Foundationimport SwiftData@Model// allow you to save data making use of SwiftData finalclassItem{// FINAL = this class can not be changedvar timestamp: Dateinit(timestamp: Date){self.timestamp= timestamp}}@ModelfinalclassTodo_Class{var titulito: Stringinit(titulito: String){self.titulito= titulito}}