core-dataswiftuipicker

SwiftUI Picker return empty string from CoreData


How to improve this? Picker returns empty String when I use ForEach (CoreData entities). If I use testing[String] everything works fine

import SwiftUI

struct AddTask: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Goal.entity(), sortDescriptors: []) var goals: FetchedResults<Goal>
    
    @State private var taskName: String = ""
    @State private var originGoal = ""
    private let testGoal = ["Alpha", "Bravo", "Charlie"]
    
    var body: some View {
        NavigationView {
            Form {
                Section{
                    TextField("Enter Task Name", text: $taskName)
                }
                Section {
                    Picker(selection: $originGoal, label: Text("Choose Goal")) {
                        ForEach(goals, id: \.self) { goal in
                            Text(goal.wrappedName)
                        }
                    }
                }
            }
        }
        
        Button("Add") {
            let task1 = Task(context: self.moc)
            task1.name = taskName
            task1.origin = Goal(context: self.moc)
            task1.origin?.name = originGoal
            
            try? self.moc.save()
        }
    }
}

Or maybe there are nice alternatives for SwiftUI Picker?


Solution

  • The selection and id should be the same type in Picker, so try (cannot test your code):

    Section {
        Picker(selection: $originGoal, label: Text("Choose Goal")) {
            ForEach(goals, id: \.wrappedName) { goal in
                Text(goal.wrappedName)
            }
        }
    }
    

    sometimes also tag works (but was reported not always), so try as well

    Section {
        Picker(selection: $originGoal, label: Text("Choose Goal")) {
            ForEach(goals, id: \.self) { goal in
                Text(goal.wrappedName).tag(goal.wrappedName)
            }
        }
    }