40

Following error in my preview:

struct DetailView: View {
    var header: DataProvider.DataHeader

    var body: some View {
        Text("...")
    }
}

struct DetailView_Previews: PreviewProvider {
    var a = DataProvider.DataHeader(title: "a", text: "b")

    static var previews: some View {
        DetailView(header: a)
    }
}

Error is:

Instance member 'a' cannot be used on type 'DetailView_Previews'

Why this is happening?

gurehbgui
  • 14,236
  • 32
  • 106
  • 178

3 Answers3

80

It is due to static var preview,

so use either static as well

static var a = DataProvider.DataHeader(title: "a", text: "b")

or construct in place

DetailView(header: DataProvider.DataHeader(title: "a", text: "b"))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 13
    Excellent answer. And this is yet another example of the way some programming languages are actively hostile to new users. The tool that generates an error messages like that has more than enough information to inject a hint as to why it encountered the error. – Chuck Wolber Sep 27 '20 at 21:35
  • How would I manipulate a static variable like this? – Jon Vogel Mar 03 '21 at 00:19
17

SwiftUI Preview -> You have to use static var here:

struct ErrorView_Previews: PreviewProvider {
    @State static var alert = false
    @State static var error = "Please fill all the contents properly"

    static var previews: some View {
        ErrorView(alert: $alert, error: $error)
    }
}
oskarko
  • 3,382
  • 1
  • 26
  • 26
-2

I would suggest doing something like this.

struct DetailView_Previews: PreviewProvider {
   static func getHeader()->DataProvider.DataHeader{
      var header:DataProvider.DataHeader = DataProvider.DataHeader(title: "a", text: "b")
    
      return header
   }

   static var previews: some View {
        DetailView(header: getHeader())
    }
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 17 '23 at 17:20