Getting Amibiguous use of 'init(_:traits:body:)' error with #Preview in Xcode 15.0.1
Asked Answered
L

1

5

I created a preview using the new #Preview syntax for a View and I'm getting the error Amibiguous use of 'init(_:traits:body:)':

#Preview {
    let viewModel = RecordingDetailViewModel(recording: nil, viewContext: PersistenceController.preview.container.viewContext)
    TranscribingTransitionView(viewModel: viewModel)
}

I've tried a few things to resolve it, like adding return as suggested here. Sometimes the error will go away when I build my project (and it always builds and runs on the simulator just fine), but as soon as I unpause the Preview, the error comes back.

I still get the error even when I switch back to the old syntax even though the error is showing up in an expansion of the macro that no longer exists:

struct TranscribingTransitionView_Previews: PreviewProvider {
  static var previews: some View {
    let viewModel = RecordingDetailViewModel(recording: nil, viewContext: PersistenceController.preview.container.viewContext)
    TranscribingTransitionView(viewModel: viewModel)
  }
}
Lumbricalis answered 28/11, 2023 at 19:39 Comment(3)
I've had the same issue - possibly a bug...? The only 'solution' I had was to delete the Preview code. Not a great answer to the problem, but it's possible the Preview macro compliles differently to the actual build as it's live. My code worked fine in my app just as yours did.Pouncey
Yup I ended up doing the same!Lumbricalis
Adding a return to the preview might also work: stackoverflow.com/questions/77000297Cave
C
8

The #Preview macro only supports a single View in its body. So in your specific example, the failure is due to the let. If you inline that definition it will work:

#Preview {
    TranscribingTransitionView(
        viewModel: RecordingDetailViewModel(
            recording: nil,
            viewContext: PersistenceController.preview.container.viewContext
        )
    )
}

If you need more than a single View, you can work around the limitation by wrapping it all in a stack of some kind:

#Preview {
    ZStack {
        let viewModel = //...
        TranscribingTransitionView(viewModel: viewModel)
    }
}
Cave answered 12/4, 2024 at 17:45 Comment(2)
Solved my issue. Thanks!Plumber
This made me nuts - the let worked fine when I was working in an SPM package's repo, worked fine when I integrated that package to an app, but failed the build on CI. Thank you for the answer!Schoenburg

© 2022 - 2025 — McMap. All rights reserved.