I have a generic function that fetches from DB objects based on a given type and filter:
class Employee: Object {
@objc dynamic var id: String = UUID().uuidString
@objc dynamic var hardWorking = false
}
class Student: Object {
@objc dynamic var id: String = UUID().uuidString
@objc dynamic var regular = false
}
enum Filter {
case all
case regularStudents
case hardWorkingEmployees
}
func fetch<T: Object>(_ type: T.Type, filter: Filter) -> [T] {
var predicate: NSPredicate?
switch filter {
case .regularStudents: predicate = NSPredicate(format: "regular = %@", NSNumber(true))
case .hardWorkingEmployees: predicate = NSPredicate(format: "hardWorking = %@", NSNumber(true))
default: break
}
guard let filterPredicate = predicate else {
return realm!.objects(type).toArray()
}
return realm!.objects(type).filter(filterPredicate).toArray()
}
I want to throw a compile error when this function is call and the given type mismatch the given filter. E.g.: You can not apply .regularStudents filter on Employees.
let students = fetch(Employee.self, filter: .regularStudents) // a compile error should be throw
I was thinking of using #if
and #error()
to throw a compile error but I could not find a solution to declare custom compiler directives in swift. In Objective C I would do something like:
#define CHECK(param1, param2) param1 == param2
Is there any way to do this custom #define
in swift?
Update
For persitance I use Realm which gives me the posibility the fech objects from a given table based on a type. The .all
filter works on all types since it fetch all objects for the given type.
The problem appear on the last two filters that depends on a specific type. For example .regularStudents
works only for Student
type, for any other type will crash since regular
property is only part of the student object.