Result of query as parameter in call

Using SwiftData I have " @Query var hands: [Hand]". My understanding is that the variable hands will be an array of Hand objects. The is in my view.

I have a function, in a different class, that adds to this array. As the parameter for the function I have " hands: inout [Hand]", It is inout cause in the function I have "hands.append"

The call looks like "common.record(hands: &hands" I get an error "Cannot pass immutable object..."
I understand, kind of, why I get the error. I am trying to use an object I can not change, the hands array, passing it as something I will change.
If I declare a variable as an array of [Hand] I can use it in the call, cause I defined as a variable. I think my problem is that the variable created by the @query is a let, not a var.
I know frameworks like to do things their way and I do not fully understand swift so is there a way swift would like me to do this?
I have a view, that does not itself use the array, and the array is backed by data kept in SwiftData. When I press a button I want to call a function that will add an element to the array.

@Query is a macro and will expand to something like:

@Query
var hands: [Hand]
{
    get {
        _people.wrappedValue
    }
}
private(set) var _hands: SwiftData.Query<[Hand].Element, [Hand]> = .init()

You can see that it defines the hands variable with a getter, and not a setter, which is at least the immediate cause of the given error.

At the same time though, you are not supposed to edit Query defined variables directly and instead insert to the local model context. The Query variable will update with the new changes and by effect cause your view to update.

You may want to take a look at SwiftData sample projects, although I cannot personally verify it will help.

Lastly, you will get more help on the Apple Developer Forums since SwiftData is a private framework and separate from the Swift programming language.

1 Like