CleanMyFloor
CleanMyFloor

Reputation: 41

SwiftUI TextField with dictonary

I have several text fields and I would like to save all entries in a dictonary.

My dictonary:

@State var fieldInput: [String: Binding<String>] = [:]

My TextField:

TextField("Name", text: fieldInput["Name"]!)

Unfortunately, I always get this error when I want to access the view with the TextFields.

Fatak error: Unexpectedly found nuk while unwrapping an Optional value

Upvotes: 1

Views: 912

Answers (2)

swiftPunk
swiftPunk

Reputation: 1

    struct ContentView: View {
    
    @State var fieldInput: [String: String] = [:]
    
    @State var value: String = String() {
        didSet {
            fieldInput["Name"] = value
        }
    }
    
    var body: some View {

        TextField("Enter your name here . . .", text: $value)

    }
}

Upvotes: 0

Asperi
Asperi

Reputation: 258443

Dictionary is not sequence container, so every entry in it not persistent on change, so you cannot bind to it, so this is not even allowed.

Here is possible approach

@State var fieldInput: [String: String] = [:]
@State private var name = ""

..

TextField("Name", text: $name)
   //.onReceive(Just(name)) {      // << iOS 13.+ (needs import Combine)
   .onChange(of: name) {
      fieldInput["Name"] = $0      // << here !!
   }

Upvotes: 1

Related Questions