SwiftData predicate filtered by enum case

I have several Swift Data types with a property of type enum. Whenever I've tried to write a predicate returning data objects only of a certain enum case, the compiler throws an error from the macro at build time. (which I don't have handy, sorry...). Is this supported? And if so, how would you write the predicate?

@Model
public final class AlbumList {
    // ...
    public var listType: AlbumListType
    // ...
}

public enum AlbumListType: String, CaseIterable, Codable {
    case listener
    case dj
}
Answered by Frameworks Engineer in 891882022

To fetch all AlbumList models whose listType is AlbumListType.listener, the predicate would be:

let target = AlbumListType.listener
let predicate = #Predicate<AlbumList> { $0.listType == target }

Note that the right-hand side is declared on its own line and captured. Putting AlbumListType.listener directly in the builder closure may lead to an error from the macro.

Accepted Answer

To fetch all AlbumList models whose listType is AlbumListType.listener, the predicate would be:

let target = AlbumListType.listener
let predicate = #Predicate<AlbumList> { $0.listType == target }

Note that the right-hand side is declared on its own line and captured. Putting AlbumListType.listener directly in the builder closure may lead to an error from the macro.

@Frameworks Engineer thank you so much!! I figured there had to be a way

SwiftData predicate filtered by enum case
 
 
Q