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
greetingbeforeinit()where would that be?preinit()? - Why does it think
greetingis 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
lengthis ofIntrather thanMeasurement?