PreviewProvider view initializer compiler error

I'm experienced in many ways, but new to Swift and SwiftUI. After a lot of studying, I've been able to get my little test project going OK, but I've run into a trivial error that I just don't know enough to figure out, and I've tried. I've reduced it to this toy:

import SwiftUI

struct Root {
  var register = 3
  var degree = 0
}

struct RootView: View {
  var rootToView: Root

  var body: some View {
    Text("[10, 10]")
  }
}

struct RootView_Previews: PreviewProvider {
  static var previews: some View {
    RootView(rootToView: Root)  // ERROR
  }
}

This gives the compiler error, "Cannot convert value of type 'Root.Type' to expected argument type 'Root'"

My project runs fine in the simulator, but of course I want the Canvas to work, and most importantly, I need to understand what's expected as the argument for RootView in the provider. Can someone please explain?

Answered by robnotyou in 706804022

For a more general solution, in your PreviewProvider:

  • create an instance of the type you are using (Root)
  • configure it (if necessary)
  • pass it to RootView
struct RootView_Previews: PreviewProvider {
    static var previews: some View {
        let root = Root()
        /// configure root, if necessary, e.g. root.register = 5
        return RootView(rootToView: root)
    }
}

You have to create an instance of class Root in our preview like this: RootView(rootToView: Root())

Accepted Answer

For a more general solution, in your PreviewProvider:

  • create an instance of the type you are using (Root)
  • configure it (if necessary)
  • pass it to RootView
struct RootView_Previews: PreviewProvider {
    static var previews: some View {
        let root = Root()
        /// configure root, if necessary, e.g. root.register = 5
        return RootView(rootToView: root)
    }
}
PreviewProvider view initializer compiler error
 
 
Q