If you are interested in more in-depth overview of how selection works, check out selection documentation.
Simple Queries
To kick things off, let’s start with a simple Hello World query:- first create a
Selection.Querysince we are going to select a field in the rootQuery. This is a generic type that can be used to query any type of data. In this case, we’re querying aStringvalue, that’s why we particularize the generic to return a string. - Second, we create a closure that will be called to create a selection and to decode returned value. That closure will receive a
QueryBuilderas the only argument which lets us select fields available in that type - in our caseworldfield in theQuerytype. - Lastly, we assign the selection to a value
helloso we can reuse it in many places.
Reusing Selection
Once we’ve create a selection, we can reuse it in any other query just like a GraphQL fragment. This way, we can compose complex queries from simple ones and keep track of all the selections we’ve created.Notice that instead of always relying onbuilderargument, we use$0to refer to theQueryBuilderinstance.
Decoding Values
Since selection is just another Swift function, we can add custom logic to how we decode values. For example,- we might want to make sure that each message has an author even if schema doesn’t enforce it,
- we could convert a
Stringvalue to anURLand fail if it’s not a valid URL, - we could convert an object into a discriminated union, or
- we could even filter out the data from a list that doesn’t fit our needs.
It’s important that you always make selection before any logical operation on it. Otherwise, it could happen that some fields are missing from the selection.
Adding Arguments
GraphQL operations often require arguments. SwiftGraphQL lets you pass arguments to your selections as arguments to selected fields. Furthermore, if you want to make your query dynamic, you can create a function that returns selection instead of creating a variable.Optional Arguments
GraphQL differentiates between different kinds of absent variables when dealing with inputs. A variable may be- present (e.g. “21 years old”)
- null (e.g. “we don’t know how old a person is”)
- missing (e.g. “we shouldn’t change the current value”).
OptionalArgument enumerator.
NOTE: Every nullable argument is by default absent so you don’t have to write boilerplate code.Because writing
OptionalArgument is cumbersome, SwiftGraphQL provides a convenience operator ~ that transforms scalar values into present optional arguments.