swiftuipreview

Instance member cannot be used on type in SwiftUI Preview


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?


Solution

  • 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"))