How to initialize state variable in SwiftUI view?


Have this code, but did not do the job. Sometimes key is set during view initialization.

struct EditApiView: View {
    @EnvironmentObject var sharedState: SharedState
    @State private var isLoaded = false
    @State private var input1 = ""
    @State private var input2 = ""
    @State private var input3 = ""
    @State var key: String?
    init() {
        key = "test"

Tried this also, did not work:

key = State(initialValue: "test")

>Solution :

Have you tried setting it with _key = State(initialValue: "test") in the init function?

See also:

Leave a ReplyCancel reply