1

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?

2
  • What do you mean by Picker return empty String? Commented Aug 6, 2020 at 9:34
  • Picker don't choose any variant from Goals List, show, but don't select Commented Aug 6, 2020 at 11:29

1 Answer 1

1

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)
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.