Isn't this a bug?
class ConnectionWatcher : ObservableObject {
static let shared = ConnectionWatcher()
@Published var connected = false
}
struct ConnectedView: View {
@ObservedObject var watcher = ConnectionWatcher.shared
@Binding var connected: Bool
init() {
// compiler error here: ''self' used before all stored properties are initialized
self._connected = $watcher.connected
}
var body: some View {
Text(connected ? "Connected" : "Working offline")
}
}
The compiler is wrong, isn't it? Is there anything I can to initialize this the way I want to?
How the heck do I do this without requiring that someone above me pass in the binding to me?
(And no, I don't want to do an @EnvironmentObject).
Lantua
2
init() {
_connected = .constant(false)
_connected = $watcher.connected
}
but I'd strongly suggest that you just use watcher.connected, and $watcher.connected.
Thanks. I’m glad to see how to do it, but I realized exactly as you said, that given that I am observing the entire instance, I don’t actually need a binding to connected. I’m going to rebuild the view anyway when the watcher object changes.
And as a PS I understand why the message isn’t erroneous now.
If you break it down to
init() {
let rhs = self.$watcher.connected
_connected = rhs
}
it becomes obvious the error message is correct.