Closure | Error when referring static variable

struct Preview: View {
    private static let NAME = "Test"

    @Query(filter: #Predicate<Item> { $0.name == Preview.NAME})
    private var items: [Item]

    var body: some View {
        MyView(name: Preview.NAME, items: items)
    }
}

Compile error occurs: key path cannot refer to static member 'NAME' How can a (static) constant be referred in member closure?

Answered by Frameworks Engineer in 791142022

Unfortunately #Predicate does not support referencing static properties. Can you redesign your view such that this value is not in a static property?

You can refer to a static variable. As shown in the small code below:

struct Preview: View {
    private static let NAME = "Test"
    var array: [String] = ["someTest", "Hello", "HelloTest"]
    var filtered: [String] {
        array.filter { $0.contains(Preview.NAME) }
    }

    var body: some View {
        ForEach(filtered, id: \.self) { s in
            Text(s)
        }
    }
}

So the problem is the use in the Query. May be you could try to include in a computed var ?

Accepted Answer

Unfortunately #Predicate does not support referencing static properties. Can you redesign your view such that this value is not in a static property?

Closure | Error when referring static variable
 
 
Q