I'm having troubles with passing class information from one struct instance to another, so I've been messing trying things out.
This works because I'm passing through Views
// phone_testingApp.swift
import SwiftUI
@main
struct phone_testingApp: App {
@ObservedObject var myObservedObject = MyObservedObject()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(myObservedObject)
}
}
}
// ContentView.swift
import SwiftUI
import Combine
struct ContentView: View {
var subtract = MinusToObject()
@EnvironmentObject var myNumber: MyObservedObject
var body: some View {
VStack{
Text("The number is \(myNumber.theObservedObjectToPass)")
MinusToObject()
.environmentObject(myNumber)
}
}
}
class MyObservedObject: ObservableObject {
@Published var theObservedObjectToPass = 5
}
struct MinusToObject: View {
@EnvironmentObject var theObservedObject: MyObservedObject
var body: some View {
Text("Minus")
.onTapGesture {
theObservedObject.theObservedObjectToPass -= 1
}
}
}
but if I try something similar with just a plain struct that doesn't conform to View like this
import SwiftUI
import Combine
struct ContentView: View {
var subtract = MinusToObject()
@EnvironmentObject var myNumber: MyObservedObject
var body: some View {
VStack{
Text("The number is \(myNumber.theObservedObjectToPass)")
Text("Minus")
.onTapGesture {
subtract.subtractIt()
}
}
}
}
class MyObservedObject: ObservableObject {
@Published var theObservedObjectToPass = 5
}
struct MinusToObject {
@EnvironmentObject var theObservedObject: MyObservedObject
func subtractIt() {
theObservedObject.theObservedObjectToPass -= 1 //Thread 1: Fatal error: No ObservableObject of type MyObservedObject found. A View.environmentObject(_:) for MyObservedObject may be missing as an ancestor of this view.
}
}
I get a runtime error thats I've put commented in at the calling of the function.
I'm quite confused as to how to pass around an instance of a reference type, so I'm sure I'm doing many things wrong, and any help would be appreciated.