I'm missing something basic here but I am unable to to get the SwiftUI function to save a new file and delete the old one

it should be creating a new file and saving it, and then deleting the original file. iv'e attempted to have it load the UUID and by the title to avoid the need to even have the correct filename....

import SwiftUI

struct file1DetailView: View {
    var file1: file1
    @Binding var showFile1: Bool
    var saveFile1: ((file1) -> Void)
    
    @Environment(\.presentationMode) var presentationMode
    
    @State private var addFile1View: AddFile1View?
    
    var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        return formatter
    }
    
    var timeFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        return formatter
    }()
    
    var body: some View {
        ZStack {
            ScrollView {
                VStack {
                    VStack{
                        HStack{
                            Text(file1.title)
                                .font(.largeTitle.weight(.semibold))
                                .foregroundColor(.BrandGreen)
                                .disabled(true)
                            Spacer()
                        }
                        Spacer()
                            .frame(height: 5)
                        
                        HStack{
                            Text(dateFormatter.string(from: file1.date))
                                .foregroundColor(.BrandGreen)
                                .font(.subheadline.weight(.light))
                            Text(timeFormatter.string(from: file1.date))
                                .foregroundColor(.BrandGreen)
                                .font(.subheadline.weight(.light))
                            
                            Spacer()
                        }
                        
                        Spacer()
                            .frame(height: 15)
                        
                        Text(file1.description)
                            .foregroundColor(.BrandGreen)
                            .disabled(true)
                        
                        Spacer()
                            .frame(height: 10)
                        
                    }
                    .padding()
                    .background(Color.white)
                    .cornerRadius(30)
                    
                    Spacer()
                    
                }
                Spacer()
                
            }
            .background(
                Image("calm-gradient")
                    .resizable()
                    .edgesIgnoringSafeArea(.all)
            )
            
            VStack {
                Spacer()
                
                Button("Start file1") {
                    let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: Date(), preventible: false, Option1: "", Option2: "")
                    addFile1View = AddFile1View(id: file1.id, file1: newFile1, saveFile1: saveFile1)
                    showFile1 = true
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 15)
                .foregroundColor(.white)
                .background(Color("BrandGreen"))
            }
        }
        .fullScreenCover(item: $addFile1View) { view in
            NavigationView {
                view
                    .onDisappear {
                        showFile1 = false
                        presentationMode.wrappedValue.dismiss()
                    }
            }
        }
    }
}

struct AddFile1View: View, Identifiable {
    var id: UUID
    @Environment(\.presentationMode) var presentationMode
    @State private var preventible = false
    @State private var Option1 = ""
    @State private var Option2 = ""
    @State private var reflectionDate = Date()
    
    var file1: file1
    var saveFile1: ((file1) -> Void)?
    
    // AddFile1View initializer
    init(id: UUID, file1: file1, saveFile1: ((file1) -> Void)?) {
        self.id = id
        self.file1 = file1
        self.saveFile1 = saveFile1
    }
    
    var body: some View {
        VStack {
            Toggle("Preventible", isOn: $preventible)
            TextField("Option1", text: $Option1)
            TextField("Option2", text: $Option2)
            DatePicker("file1 Date", selection: $reflectionDate)
            
            Button("Save") {
                let newFile1 = file1(title: file1.title, description: file1.description, date: file1.date, reflectionDate: reflectionDate, preventible: preventible, Option1: Option1, Option2: Option2)
                saveFile1?(newFile1)
                presentationMode.wrappedValue.dismiss()
            }
        }
        .navigationTitle("Add file1")
    }
}

func saveFile1(file1: file1) {
    let encoder = JSONEncoder()
    let fm = FileManager.default
    let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
    let file1sURL = documentsDirectory.appendingPathComponent("file1s.json")
    
    // Read the existing file1s from the file system
    var file1s: [file1] = []
    if fm.fileExists(atPath: file1sURL.path) {
        do {
            let data = try Data(contentsOf: file1sURL)
            file1s = try JSONDecoder().decode([file1].self, from: data)
        } catch {
            print("Failed to read file1s from file system: \(error)")
        }
    }
    
    // Add the new file1 to the list
    file1s.append(file1)
    
    // Write the updated list back to the file system
    do {
        let data = try encoder.encode(file1s)
        try data.write(to: file1sURL)
        print("file1s saved to device: \(file1s)")
        print("file1s file URL: \(file1sURL)")
    } catch {
        print("Failed to save file1s: \(error)")
    }
    
    // Delete the old file1 file
    let oldFile1URL = documentsDirectory.appendingPathComponent("\(file1.id).json")
    if fm.fileExists(atPath: oldFile1URL.path) {
        do {
            try fm.removeItem(at: oldFile1URL)
            print("Deleted old file1 file: \(oldFile1URL.lastPathComponent)")
        } catch {
            print("Failed to delete old file1 file: \(error)")
        }
    }
}

struct file1DetailView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            file1DetailView(
                file1: file1(
                    title: "Example file1",
                    description: "This is an example file1 description.",
                    date: Date(),
                    file1Date: Date(),
                    preventible: true,
                    Option1: "Example Option1",
                    Option2: "Example Option2"
                ),
                showFile1: .constant(false),
                saveFile1: saveFile1
            )
        }
    }
}

Replies

Thank you for any help. although this code isn't printing it (as iv'e rewrote multiple times I suspect that its not receiving the name of the original file which is saved like this

struct File1: Codable, Identifiable {
    var id = UUID()
    var title: String
    var description: String
    var date: Date
    var preventible: Bool
    var Option1: String
    var Option2: String
    var file1Date: Date
    
    init(title: String, description: String, date: Date, file1Date: Date, preventible: Bool, Option1: String, Option2: String) {
        self.title = title
        self.description = description
        self.date = date
        self.preventible = preventible
        self.Option1 = alternateHandling
        self.Option2 = alternatePerspective
        self.file1Date = reflectionDate
    }
}

Creation:

import SwiftUI

struct File1View: View {
    @State private var title = ""
    @State private var description = ""
    @State private var date = Date()
    @State private var preventible = false
    @State private var Option1 = ""
    @State private var Option2 = ""
    @State private var File2Date = Date()
    
    @Environment(\.presentationMode) var presentationMode
    
    static func saveFile1(_ file1: File1) {
        let fm = FileManager.default
        let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
        let file1sDirectory = documentsDirectory.appendingPathComponent("file1s")
        let file1File = file1sDirectory.appendingPathComponent("\(file1.id).json")
        do {
            let encoder = JSONEncoder()
            encoder.outputFormatting = .prettyPrinted
            let data = try encoder.encode(file1)
            try fm.createDirectory(at: file1sDirectory, withIntermediateDirectories: true, attributes: nil)
            try data.write(to: file1File, options: .atomic)
        } catch {
            print("Failed to save file1: \(error.localizedDescription)")
        }
    }
    
    var body: some View {
        NavigationView {
            VStack {
                TextField("Title", text: $title)
                TextField("Description", text: $description)
                DatePicker("Date", selection: $date)
                
                VStack {
                    Toggle("Preventible", isOn: $preventible)
                    TextField("Option1", text: $Option1)
                    TextField("Option2", text: $Option2)
                    DatePicker("File2Date", selection: $File2Date)
                }
                .hidden()
                
                Button("Save") {
                    let file1 = File1(title: title, description: description, date: date, File2Date: File2Date, preventible: preventible, Option1: Option1, Option2: Option2)
                    File1View.saveFile1(file1)
                    presentationMode.wrappedValue.dismiss()
                }
            }
        }
    }
}