I build a Swift function to get an object by id of a specific SwiftData class, which works fine. Now I try to rebuild this into a generic function to use with different classes. My code looks like this:
func getObjectByID<T: PersistentModel>(context: ModelContext, id: Int) -> T? {
do {
let predicate = #Predicate<T> {
id == $0.id
}
let descriptor = FetchDescriptor<T>(predicate: predicate)
let objects = try context.fetch(descriptor)
return objects.first
} catch {
return nil
}
}
A get 2 errors:
- The line with id == $0.id has an error: “Operator function ‘==’ requires that ‘PersistentIdentifier’ conform to ‘BinaryInteger'”
- The line with let objects = try context.fetch(descriptor) has an error: Generic parameter ‘T’ could not be inferred
Why do I get these errors and how can I solve these problems?
I tried (context: ModelContext, id: any BinaryInteger) with no success
3
If you want a function for model types that uses an id
of type Ìnt
only then you need to limit what types the function can be used for using a where
condition
func getObjectByID<T: PersistentModel>(context: ModelContext, id: Int) -> T? where T.ID == Int
Using this your code will compile.
Another option is to create a specific protocol for this that specifies the type of the id
property
protocol RestApiModel: PersistentModel {
var id: Int { get }
}
And then you declare the function as
func getObjectByID<T: RestApiModel>(context: ModelContext, id: T.ID) -> T? {
2