Question about using @Previewable

This is an issue that occurred while using SwiftUI.

Cannot find '$state' in scope

The other view finds properties normally. May I know why the error is occurring?

The following code is the full text of the code that causes problems.

import SwiftUI
@Observable
class HomeState {
var title: String = "Home"
}
struct HomeView: View {
@Binding var state: HomeState
var body: some View {
Text(state.title)
}
}
#Preview {
@Previewable @State var state: HomeState = .init()
HomeView(state: $state) /// Error: Cannot find '$state' in scope
}

The same error occurs when using the String type rather than the object. What did I do wrong?

Answered by huisoo in 828781022
struct State {
// code...
}

I found the cause
The problem was that created this struct....

Hi,

Sorry to hear you are having problems getting previews working. Thanks for providing a code snippet that reproduces the issue for you. I am unable to reproduce this with the snippet as the preview loads fine for me. One thing you could try is to rename the state variable to something that doesn't happen to match the lowercased version of the property wrapper, so:

#Preview {
@Previewable @State var somethingElse: HomeState = .init()
HomeView(state: $somethingElse)
}

and see if that works for you?

If not, the best next step will be to file a feedback with diagnostics so we can take a look.

We will need the diagnostics Xcode Previews generates in order to make sure we understand the error the previews system is encountering.

Install the logging profile using instructions available here: https://developer.apple.com/bug-reporting/profiles-and-logs/?name=swift On your mac running Xcode, and on your physical preview device (if you are using one).

Install the logging profile using the following instructions on your mac running Xcode; and if you are using one, your physical preview device (iOS or visionOS): https://developer.apple.com/bug-reporting/profiles-and-logs/?name=swift

Then when you reproduce the problem in Xcode:

  1. Either (a) an error banner will appear, click the "Diagnostics" button in that banner; or (b) if you're not seeing an error but you still want to provide diagnostics you can get the same diagnostics window by going under the Editor menu in the menu bar, then selecting the Canvas submenu, then selecting "Diagnostics".
  2. In the sheet that appears, click "Generate Report" in the bottom left of the sheet
  3. Attach (or make from the folder) the resulting zip file to the bug (will be named something like previews-diagnostics-0123456789.zip)
  4. Generate a sysdiagnose on your mac and any on-device preview devices, and attach those too
Accepted Answer
struct State {
// code...
}

I found the cause
The problem was that created this struct....

Question about using @Previewable
 
 
Q