Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch with new #Predicate macro by Enum property

I’m trying to fetch some results with the new #Predicate macro. The problem appears when I try to use an enum property inside the predicate. Does anyone know if it can be done or if this is a bug?

XCode 15 beta 4

Fetch 1:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let predicate = #Predicate<ModelA> { $0.type == ModelA.ModelAType.a }

Fetch 2:

let predicate = #Predicate<ModelA> { $0.type.rawValue == ModelA.ModelAType.a.rawValue }

Model:

@Model final class ModelA: Codable {
    @Attribute(.unique) var id: Int64 = 0
    enum ModelAType: Int, CaseIterable, Codable { case a = 1, b }
    var type: ModelAType = ModelAType.a
}

Errors:

Type 'ModelA.Type' cannot conform to 'StandardPredicateExpression'
Type 'ModelA.Type' cannot conform to 'PredicateExpression'
Cannot infer key path type from context; consider explicitly specifying a root type

>Solution :

What worked for me in this situation was to define a constant for the raw value and use that constant in the predicate

let aValue = ModelA.ModelAType.a.rawValue
let predicate = #Predicate<ModelA> { $0.type.rawValue == aValue }

I am not sure why this is needed but hopefully it’s a beta thing that will change soon

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading