Error after adding previewContainer during code-along

I am getting this error in my preview:

CompileDylibError: Failed to build ContentView.swift

Compiling failed: main actor-isolated let 'previewContainer' can not be referenced from a non-isolated context

I don't know enough about @MainActor to figure this out.

Accepted Reply

Yes, this is a known issue. You can work around it as suggested by using MainActor.assumeIsolated:

#Preview {
    MainActor.assumeIsolated {
        ContentView()
            .frame(minWidth: 500, minHeight: 500)
            .modelContainer(previewContainer)
    }
}
  • Hey, Developer Tools Engineer, Julia is an excellent presenter! If you see her, could you please correct her pronunciation of "model"? She makes it sound like "modal", which was a bit distracting. And give her a thumbs up for her good teaching style.

Add a Comment

Replies

This looks like an issue with some aspect of the #Preview macro implementation.

I replaced it with the old-style preview syntax and bypassed this issue:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
            .modelContainer(previewContainer)
    }
}
  • "I encountered the same issue in Xcode 15.0 beta, SwiftDataExample, and I was able to resolve it using this method."

Add a Comment

I kept the #Preview macro by changing it to this, but with warnings about losing global actor 'MainActor':

#Preview { @MainActor in
    ContentView()
        .frame(minWidth: 500, minHeight: 500)
        .modelContainer(previewContainer)
}

@Apple, is this a bug in this early beta stage or will the sample code be modified to get around this behavior ?

I asked Chatgpt for this question, and it told me this: #Preview { MainActor.assumeIsolated { ContentView() .frame(minWidth: 500, minHeight: 500) .modelContainer(previewContainer) } } It worked.

  • This did it for me, thanks so much.

Add a Comment

Yes, this is a known issue. You can work around it as suggested by using MainActor.assumeIsolated:

#Preview {
    MainActor.assumeIsolated {
        ContentView()
            .frame(minWidth: 500, minHeight: 500)
            .modelContainer(previewContainer)
    }
}
  • Hey, Developer Tools Engineer, Julia is an excellent presenter! If you see her, could you please correct her pronunciation of "model"? She makes it sound like "modal", which was a bit distracting. And give her a thumbs up for her good teaching style.

Add a Comment

Thanks!!