How can I send some `value` or `nil` in a graphql mutation

I was using v0.33 and recently updated it to the latest version of Apollo SDK and facing an issue:

Problem -
I want to pass either an Int value or nil to a graphql mutation. This is how I was doing it in v0.33:

 func callService(value: Int) {
        // The `value` can be any Int number or nil
        let limitValue = value == 0 ? nil : value
        let setLimitMutation = SetLimitNumberMutation(value: limitValue)
        // Then I call my perform mutation code
}

After updating the SDK to the latest version

 func callService(value: Int) {
        // The `value` can be any Int number or nil
        let limitValue = value == 0 ? nil : value
        let setLimitMutation = SetLimitNumberMutation(value: .some(limitValue ?? 0))
        // Then I call my perform mutation code
}

If I don’t provide coalesce default value, the compiler throws an error:

 let setLimitMutation = SetLimitNumberMutation(value: .some(limitValue))
 Error -> Value of optional type 'Int?' (aka 'Optional<Int>') must be unwrapped to a value of type 'Int' (aka 'Int')

If I don’t provide .some(value) and use value with coalesce, the nil is replace by default value 0:

 let setLimitMutation = SetLimitNumberMutation(value: limitValue ?? 0)

How can I send nil or a value in that mutation? Please help.

You’ll need to use the .none case of the GraphQLNullable enum. If you want to omit the value completely, use .none. If you want to send the value as null, use the .null case.

let limitValue: GraphQLNullable<Int> = value == 0 ? .none : .some(value)

For more information about why this is, check out this blog post!

1 Like

It worked like a charm! Thank you very much for such a quick reply. I tried with .none and .null but not as you suggested. Thanks again!

1 Like