Cannot use instance member 'name' within property initializer; property initializers run before 'self' is available

Hello
Why does it give me an error when I pass 'name' at line 3?
Code Block
struct OtherView: View {
@State private var name: String = ""
@ObservedObject var use = Use(name: name)
var body: some View{
VStack{
}
}
}
class Use: ObservableObject {
@Published var name: String
init(name: String) {
self.name = name
}
}


Thank you

Answered by Claude31 in 670207022
In fact the message is pretty explicit.

You try to use self (by using its name property) before self is fully initialised (use is not yet defined).
That's a classical catch 22 situation in init.

Unfortunately, you cannot declare use as lazy because it is an observedValue.

But this should work
Code Block
struct OtherView: View {
@State private var name: String = ""
@ObservedObject var use : Use = Use(name: "")
init() {
use = Use(name: name)
}
var body: some View{
VStack{
}
}
}


Why not simply write
Code Block
@State private var name: String = ""
@ObservedObject var use = Use(name: "")

Have a look here for some details:
https://developer.apple.com/forums/thread/128366
Accepted Answer
In fact the message is pretty explicit.

You try to use self (by using its name property) before self is fully initialised (use is not yet defined).
That's a classical catch 22 situation in init.

Unfortunately, you cannot declare use as lazy because it is an observedValue.

But this should work
Code Block
struct OtherView: View {
@State private var name: String = ""
@ObservedObject var use : Use = Use(name: "")
init() {
use = Use(name: name)
}
var body: some View{
VStack{
}
}
}


Cannot use instance member 'name' within property initializer; property initializers run before 'self' is available
 
 
Q