Sorry for the non-sense example. Tried to simplify it, still don’t get what’s going on. The following gives me Variable 'self.greeting' used before being initialized
:
struct MyView: View {
@State var greeting: String
var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
init() {
greeting = "Hello, World!" // Variable 'self.greeting' used before being initialized
}
var body: some View {
Text(greeting)
}
}
While this is working fine (var length
differs; otherwise identical):
struct MyView: View {
@State var greeting: String
var length = 5 // now Int
init() {
greeting = "Hello, World!"
}
var body: some View {
Text(greeting)
}
}
Also, this is working (here I removed the @State
):
struct MyView: View {
var greeting: String // @State removed
var length = Measurement<UnitLength>(value: 5, unit: UnitLength.miles)
init() {
greeting = "Hello, World!"
}
var body: some View {
Text(greeting)
}
}
- If the compiler wants me to initialize
greeting
beforeinit()
where would that be?preinit()
? - Why does it think
greeting
is being “used” uninitialized when actually I am initializing it here? - Is there a different way to initialize @State vars? If so, why does it work when the unrelated var
length
is ofInt
rather thanMeasurement
?
var length = 5
works though. It shouldn't work in my opinion. – Demented@State
variables inside theinit
method. But you MUST just get rid of the default value which you gave to the state and it will work as desired” – 2022-02-12 https://mcmap.net/q/125478/-swiftui-state-var-initialization-issue (so my example should work, as it does in the version with the Int-length) – Bonne