GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Assign a value to an optional when sheet is presented

Forums > SwiftUI

Hi guys,

can anyone help me with the following.

I have declared an optional Allocation. When I tap on the plus button the function generateNewAllocation create a new one from the default and then assign it to the optional allocation.

The problem is that the first time I tap on the + button it would assign nil as it presents a blank sheet, but if I dismiss it and tap again the value is correctly assigned.

I have checked the function which correctly returns the expected allocation, but can't figure out what is going wrong.

Thanks.

import SwiftUI
import SwiftData

struct AllocationsView2: View {
    @Environment(\.modelContext) var modelContext
    @Environment(\.dismiss) var dismiss

    @State private var showEmployees = false
    @State private var allocation: Allocation?
    @State private var isSaved = false

    @Query(filter: #Predicate<Allocation> {allocation in
        allocation.isSetup == false
    }) var allocations: [Allocation]

    var body: some View {
        NavigationStack {
            List {
           /*if let unwrappedAllocation = allocation {

                    Text(unwrappedAllocation.shift)
                    ForEach(unwrappedAllocation.areas) {area in
                        Text(area.name)
                    }
               }*/
            }

            .navigationTitle("Allocations List")
            .toolbar{
                Button(action: {

                   modelContext.autosaveEnabled = false
                   let newAllocation = generateNewAllocation()
                    allocation = newAllocation
                    showEmployees = true

                }) {
                    Image(systemName: "plus")
                }
                .sheet(isPresented: $showEmployees) {
                   if  let currentAllocation = allocation {
                        Employees(allocation: currentAllocation, dismissView: $showEmployees, isSaved: $isSaved)

                    }
                }
            }

        }

    }

    func generateNewAllocation() -> Allocation? {
        var fetchDescriptor = FetchDescriptor<Allocation>(predicate: #Predicate  { allocation in
            allocation.isSetup == true
        })
        fetchDescriptor.fetchLimit = 1
        do {
            let result = try modelContext.fetch(fetchDescriptor)
            let allocationFirst = result.first

            let newAllocation = Allocation(id: UUID(), date: .now, shift: "Short Day", isSetup: false)
            modelContext.insert(newAllocation)
            if let areas = allocationFirst?.areas {
                for area in areas {
                    let newArea = Area(id: UUID(), name: area.name, order: area.order, priority: area.priority, isActive: area.isActive)
                    modelContext.insert(newArea)
                    newAllocation.areas.append(newArea)
                   // print(area.name)
                }
            }
            for area in newAllocation.areas {
                print(area.name)
            }
            return newAllocation

        } catch {
            print("failed to load Default Allocation")
            return nil
        }
    }

}

3      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.