Create an @State variable based on a Swiftui @Query

365 Views Asked by At

I have a SwiftData model and I want to use it with @Query that gets created when the app starts. And then I want to base an @State variable on that @Query variable.

Like this (this is what I am shooting for, I know it does not work):

struct Test_Beta_1App: App {
    @Environment(\.modelContext) var context

    @Query var users: [User]

    var randomHobby: String = {
         users.map { $0.hobby }.randomElement()!
    }


    ...
}

Again, when the app starts, I want to be able to choose a hobby at random and then pass randomHobby down into the views as an @State variable.

But this causes a bunch of errors, including "Property wrapper cannot be applied to a computed property". I think I knew that you can't use @State with a computed property, but I can't see how else I can create this default value that can later change based on what happens in the views.

1

There are 1 best solutions below

1
Fran On

Ok I didn't try it but I think this should get you in the right direction:

struct Test_Beta_1App: App {
    @Environment(\.modelContext) var context

    @Query var users: [User]
    @State var randomHobby = Hobby.allCases.randomElement() //This should be an Enum with all the hobbies, and be "Codable, CaseIterable, Identifiable" so you can get a random element.

    var randomHobby: String{
        users.filter({$0.hobby == randomHobby})
    }
    ...
}

And in the body a Foreach(randomHobby) in a list that print the user with their hobby, if what you are looking for is to show all the users that has that hobby. (That is what I think you are looking for, you didn't specify what you want to achieve.)