How to initialize state variable in SwiftUI view?

Advertisements

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: https://stackoverflow.com/a/58137096/900130

Leave a ReplyCancel reply