I need to use init with SwiftUI, but I am just learning about initializers. I have found many complex examples, but I cannot understand the basics.
How to initialize different values inside init() based on value of some other var, for example based on true/false from a toggle?
EXAMPLE CODE
I was trying something like this:
import SwiftUI
struct ToggleView: View {
@State var toggleValue: Bool = true
var testValue: String
init() {
if toggleValue {
self.testValue = "true"
} else {
self.testValue = "false"
}
}
var body: some View {
VStack {
Toggle(isOn: $toggleValue) {
Text("True or false?")
}.padding()
Text("Selected value:")
Text("\(testValue)")
}
}
}
struct ToggleView_Previews: PreviewProvider {
static var previews: some View {
ToggleView()
}
}
But on line with if toggleValue { I am getting an error:
'self' used before all stored properties are initialized
I have tried changing:
var testValue: String
init() {
to:
@Binding var testValue: String
init(testValue: Binding<String>) {
But it doesn't work either. How to bind this testValue with toggle, so after taping on toggle my app would print: "Selected value: false"?
testValue
at all. Just doText("\(toggleValue)")
instead ofText("\(testValue)")
. In fact, you shouldn't have a second thing that is binded to the toggle, because SwiftUI likes a single source of truth. – Sweeper