SwiftData: Predicate using optional Codable enum

Hello,

I'm currently developing an app using SwiftData.

I want the app to use CloudKit to sync data, so I made sure all my model properties are optional.

I've defined a Codable enum as follows:

enum Size: Int, Codable {
    case small
    case medium
    case large
}

I've defined a Drink SwiftData model as follows:

@Model
class Drink {
    var name: String?
    var size: Size?
    
    init(
        name: String? = nil,
        size: Size? = nil
    ) {
        self.name = name
        self.size = size
    }
}

In one of my Views, I want to use a @Query to fetch the data, and use a Predicate to filter the data. The Predicate uses the size enumeration of the Drink model. Here is the code:

struct DrinksView: View {
    @Query var drinks: [Drink]
    
    init() {
        let smallRawValue: Int = Size.small.rawValue
        let filter: Predicate<Drink> = #Predicate<Drink> { drink in
            if let size: Size = drink.size {
                return size.rawValue == smallRawValue
            } else {
                return false
            }
        }
        
        _drinks = Query(filter: filter)
    }
    
    var body: some View {
        List {
            ForEach(drinks) { drink in
                Text(drink.name ?? "Unknown Drink")
            }
        }
    }
}

The code compiles, but when I run the app, it crashes with the following error:

Thread 1: Fatal error: Couldn't find \Drink.size!.rawValue on Drink with fields [SwiftData.Schema.PropertyMetadata(name: "name", keypath: \Drink.name, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "size", keypath: \Drink.size, defaultValue: nil, metadata: nil)]

How can I filter my data using this optional variable on the Drink model?

Thanks, Axel

SwiftData: Predicate using optional Codable enum
 
 
Q