SwiftUI Picker return 来自 CoreData 的空字符串

SwiftUI Picker return empty string from CoreData

如何改进?当我使用 ForEach(CoreData 实体)时,选择器 returns 为空字符串。如果我使用 testing[String] 一切正常

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()
        }
    }
}

或者 SwiftUI Picker 有不错的替代品吗?

selectionid 应该是 Picker 中的相同类型,所以尝试(无法测试您的代码):

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

有时 tag 也有效(但并非总是被报告),所以也试试

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