Choosing CoreData Entities from form picker

As written you are not matching the types of the array the picker and the FetchResult. See the comments

import SwiftUI

@available(iOS 15.0, *)
struct LearnView: View {
    //This is optional Language
    @State private var selectedLanguage: Language?
    //I commented out variables that are not part of the reproducible body provided
    //@State private var selectedCategory: SubCategory?
    //@State private var selectedDate = Date()
    
    @Environment(\.managedObjectContext) private var viewContext
     //This is FetchedResults<Language>
    @FetchRequest(entity: Language.entity(), sortDescriptors: []) var languages: FetchedResults<Language>
    // @FetchRequest(entity: SubCategory.entity(), sortDescriptors: []) var subCategories: FetchedResults<SubCategory>
    
    var body: some View {
        NavigationView {
            ZStack {
                Form {
                    Section("Learning Schedule") {
                        Picker("Please choose a language", selection: $selectedLanguage) {
                            //Map is needed for a plain array of languages
                            //ForEach(languages.map{$0}, id: \.self) { language in
                            //This version works too
                            //The point is to go from FetchedResults<Language> to [Language]
                            ForEach(Array(languages), id: \.self) { language in
                                
                                Text(language.name ?? "Unknown")
                                //The casting is necessary to make it an optional since your @State is an optional
                                    .tag(language as? Language)
                            }
                        }
                        Text("You selected: \(selectedLanguage?.name ?? "Unknown")")
                    }
                }
            }
        }
    }
}

@available(iOS 15.0, *)
struct LearnView_Previews: PreviewProvider {
    static var previews: some View {
        LearnView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

Leave a Comment