Greg
Greg

Reputation: 34798

SwiftUI Core Data error - "Cannot convert value of type 'FetchedResults<GCItem>' to expected argument type 'Range<Int>'"

Any ideas why I am getting this error here? I haven't had this in the past with Core Data on a separate test project.

Cannot convert value of type 'FetchedResults' to expected argument type 'Range'

SwiftUI View Code (have marked error below)

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: GCItem.entity(), sortDescriptors: []) var gcItems: FetchedResults<GCItem>

    private func addItem(title:String) {
        let newItem = GCItem(context: context)
        newItem.id = UUID()
        newItem.title = title
        do {
            try context.save()
        } catch let e as NSError {
            fatalError("Unresolved error \(e), \(e.userInfo)")
        }
    }

    var body: some View {
        NavigationView {
            VStack {
                List() {
                    ForEach(gcItems) { gcItem in   // ** ERROR HERE ***
                        HStack {
                            Text("test")
                        }
                    }
                }
                Button(action: { self.addItem(title: "Testing 123") }) {
                    Text("ADD ITEM")
                }
            }
        }
    }
}

Visual Image of Error

enter image description here

Core Data Model

enter image description here

Core Data File

enter image description here

Upvotes: 2

Views: 5165

Answers (1)

Procrastin8
Procrastin8

Reputation: 4503

GCItem needs to conform to Identifiable for that code to work. A simple empty conformance should work, as it already has an id:

extension GCItem: Identifiable { }

Upvotes: 4

Related Questions