2

I have a simple struct, that is decodable / codable and hashable.

public struct Field: Codable, Hashable {
    let key: String
    enum CodingKeys: String, CodingKey {
        case key
    }
}

In my SwiftUI, I'm creating an array, where I want to add and remove and Bind to the Struct values. But I am getting errors, that Struct is not Binding.

let decodableJSON = """
{
    "key": ""
}
"""
let settableInit: Field = try! JSONDecoder().decode(Field.self, from: decodableJSON.data(using: .utf8)!)

struct Test_view: View {
    
    @State
    var settableFields: [Field] = [settableInit]
    
    var body: some View {
        ForEach(settableFields, id: \.key) { (settableField: Field) in 
             TextField("Key", text: settableField.key)
        }

But I get an error, that settableField is not Binding. I have tried adding the settableInit as an @ObservableObject to the main Swift View, but it still doesn't work.

Is there a way, to have the View bind to Struct properties, and have TextField change these properties? It feels like something so trivial, but for some reason undoable for me.

Thank you for any pointers!

1
  • since you are dealing with a JSON try an ObservableObject with a variable with a custom {get set} that read/writes to your JSON accordingly and at the end of set use objectWillChange.send() to refresh Commented Oct 31, 2021 at 13:45

1 Answer 1

4

In Xcode13 you can use the new element binding syntax:

public struct Field: Codable, Hashable {
    var key: String
    enum CodingKeys: String, CodingKey {
        case key
    }
}

struct Demo: View {
    
    @State var settableFields: [Field] = [Field(key: "1"), Field(key: "2")]
    
    var body: some View {
        ForEach($settableFields, id: \.key) { $settableField in
            TextField("Key", text: $settableField.key)
        }
    }
}

In earlier versions of Xcode you could use the indices of the array:

struct Demo: View {
    
    @State var settableFields: [Field] = [Field(key: "1"), Field(key: "2")]
    
    var body: some View {
        ForEach(settableFields.indices, id: \.self) { index in
            TextField("Key", text: $settableFields[index].key)
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Adrian, that did the trick for me! Legend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.