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.

Answered by Developer Tools Engineer in 755431022

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

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 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.

Accepted Answer

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

Thanks!!

Error after adding previewContainer during code-along
 
 
Q