SwiftUI 2.0 CoreData issues with new project - 'Cannot find type 'Item' in scope'

I didn't find any of the others answers worked for me, but what did was:

  • Opening (ProjectName).xcdatamodel
  • Adding an attribute to the Item entity, shouldn't relly matter what, I just add "foo" of type "String"
  • Cmd-B to build (You are then free to delete the new attribute).

For a brand new project, press Command+B to build and it will be fine.


The normal Xcode clearing works for me:

  1. Clean build folder (SHIFT + COMMAND + K)

  2. Quit Xcode completely

  3. Delete the project's contents in, DerivedData/{Project Name}_some_hash

    The default location is ~/Library/Developer/Xcode/DerivedData, but if it's nowhere to be found, check the Derived Data property under, Xcode → Preferences → Locations

  4. Try again (run Xcode & build)


Firstly it's not an issue with your app but an issue with a preview. Your app works properly on the simulator. The white screen is because you need to wrap your list with NavigationView() to see add and edit button. See this answer: https://stackoverflow.com/a/66234095/15224199

After that, you will see add and edit button on the simulator. But you have to fix the preview too. It doesn't work because you have an empty entity and you need to mock it. Go to Persistance.swift and you should add similar for loop as mine to create mocked Items in preview varable:

static var preview: PersistenceController = {
    let result = PersistenceController(inMemory: true)
    let viewContext = result.container.viewContext
    for _ in 0..<10 {
        let newItem = Item(context: viewContext)
        newItem.timestamp = Date()
    }
    do {
        try viewContext.save()
    } catch {
        // Replace this implementation with code to handle the error appropriately.
        // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        let nsError = error as NSError
        fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
    }
    return result
}()

At the end make sure that your preview use those mocked values:

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
    ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}

After that, it should work perfectly fine, hope it helps. I don't know why Apple provides a template that doesn't work properly at the beginning.