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

@Frameworks Engineer thank you for sharing that!

Does this only work for the new anyAppleOS 27 and not before (like iOS 17/18/26)?

Thanks

Axel

I just tested using an Enum in a SwiftData Query Predicate only works for anyAppleOS 27 & doesn't back deploy when building on Xcode 27 🫤

On anyAppleOS 26 & below, Xcode logs "Query encountered an error: Unsupported Predicate: Captured/constant values of type 'TheEnum' are not supported"

@Frameworks Engineer do you think there is any chance to back deploy that to prior OS versions?

Thank you.

SwiftData predicate filtered by enum case
 
 
Q