For my app I use a struct
for my CoreData
persistence controller like so:
struct PersistenceController {
static var shared = PersistenceController()
// more code omitted for brevity
}
As a development asset I made an extension to the PersistenceController
to provide a special instance for previews with some sample data.
extension PersistenceController {
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
// create some sample data
return result
}()
}
Now I want to use the special preview instance with the new #Preview
macro in Xcode beta 2. The deployment target for the app is set to iOS 17.
#Preview {
var context = PersistenceController.preview.container.viewContext
return SpanList()
.preferredColorScheme(.light)
.environment(\.managedObjectContext, context)
}
But the preview fails to build due to the following error:
Type 'PersistenceController' has no member 'preview'
.
My experiments show that everything I add to the PersistenceController
via an extension is not available in the preview macro. This is no matter where I place the extension. Even when it’s placed in the same file as the PersistenceController
itself.
Am I missing something or is this intended behaviour?
I believe this may be related to the issue defined in the release notes.
#Preview can’t reference symbols in Swift type extensions when they are defined in the same module as the Preview (110671628)
Workaround: Revert to using PreviewProvider, or copy the implementation of the extension directly in to the #Preview itself or make it a global symbol