How to bind generated input types with SwiftUI components?

In the name of simplicity and using the Apollo-generated types directly how do I bind my bindable SwiftUI components directly to Apollo-generated Input types?

While the generated input models are mutable, there is no init() method, only one that requires all the values to be known at initialisation time and another one that accepts an InputDict type.

It would seem overkill to duplicate all these models so that they can be bound or mutated and then have to create an adaptor to convert it into an identical Apollo input type.

Example:

struct MyView: View {
    // Apollo generated `Input` type
    @State var addressDetails = ClientAPI.InputAddressDetails() // Missing argument for parameter #1 in call

    var body: some View {
        Form {
            TextField("Street", text: $addressDetails.street)
            TextField("Town", text: $addressDetails.town)
            TextField("Post Code", text: $addressDetails.postcode)
            TextField("Country", text: $addressDetails.country)

            Button("Save")
        }
    }
}

I’m assuming that the fields of the input object are all non-null - is that correct?

That’s a very good point which I hadn’t considered. My thought process was because InputObjects are backed by an internal dictionary it would be possible to create empty instances and just mutate using SwiftUI bindings thus saving another layer of abstraction.

Is there any official guidance in this area?

The type-safe classes/structs Apollo iOS generates will require any non-null fields to be given at initialization. The fact that storage is backed by a Dictionary is an implementation detail that, while stable now, could be changed in the future.

If you really want to do what you’re suggesting then since the public initializer for InputDict has a default value you should be able to do this:

@State var addressDetails = ClientAPI.InputAddressDetails(InputDict())

The caveat in doing this is that you’re moving the validation entirely into your UI layer and avoiding the inherent ability of type safety to avoid easy-to-make missing required field errors.

No, I agree with your points. I was more wondering if there was a best practice with using Apollo and SwiftUI given Apollo’s aims to simplify developer productivity by generating the model layer etc.

Seamless integration with SwiftUI is certainly a gap in the library.

1 Like