Yes, I know this question has been asked before, but the accepted answers do not work for me. Those answers did indeed fix the compiler error, but when I pass 'self' to the initializer of a class from within my ContentView.init method, and that class later calls a method on ContentView, the 'self' is not the correct instance. The callback, setVpnState
sets the value of a @State variable, which should cause the UI to update. But it doesn't, and on inspection in lldb, it is clearly not the same 'self' (instance of ContentView).
Here is what I tried to do initially:
struct ContentView: View {
let iwinsController: IWiNSController
init() {
iwinsController = IWiNSController(view: self)
}
var body: some View {
.
.
.
}
func setVpnState(_ state: ButtonState) {
self.buttonAttributes = buttonConfig[state]!
}
}
As you would expect, the error I got was 'self' used before all stored properties are initialized
I then tried both of the answers to this question: 'self' used before all stored properties are initialized
Which did satisfy the compiler, but as I said, when setVpnState is called from my controller object, 'self' is incorrect.
So, what I had to do was initialize my controller without passing 'self', and then in onAppear set the view explicitly. This works. But it means in my controller I have to unwrap view
every time I use it.
It doesn't feel very 'Swifty'. I am new to Swift and would like to do this the accepted way.
struct ContentView: View {
let iwinsController: IWiNSController
init() {
self.iwinsController = IWiNSController()
}
var body: some View {
.
.
.
}.onAppear {
iwinsController.setView(view: self)
}
}
func setVpnState(_ state: ButtonState) {
self.buttonAttributes = buttonConfig[state]!
}
}