The following lines of code are added to the SceneDelegate class - in the appropriate places - ie: missions is declared as a new property of the class; the missions parameter is amended to the contentView property assignment in the scene method; and the window.rootViewController assignment within the scene method is modified with the missions environmentObject to place the data into the app environment.
let missions = MissionList()
let contentView = ContentView(missions: missions)
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(missions))
In ContentView, the @ObservedObject property wrapper is used to declare ownership of the missions data of type MissionList. Elsewhere in other views, the same property is wrapped with EnvironmentObject in order to use it. That all works lovely jubly.
However, the compiler makes a complaint when I add an @EnvironmentObject wrapper for the preview to use the same data. The error is “Instance member ‘missions’ cannot be used on type ‘ContentView_Previews’.
struct ContentView_Previews: PreviewProvider {
@EnvironmentObject var missions: MissionList
static var previews: some View {
ContentView(missions: missions)
}
}
In what would appear counterintuitive, when a static let is assigned to be an instance of MissionList, Swift is happy again. A plain let will also produce the same error, so the static key word is doing all of the magic here.
struct ContentView_Previews: PreviewProvider {
static let missions = MissionList()
static var previews: some View {
ContentView(missions: missions)
}
}
Is this a conformance issue, ie View conformance is different to PreviewProvider conformance? I really would like to understand why this is happening and whether I am even thinking about these concepts properly. Any input would be useful and I am also happy to supply more code if necessary.