So in:
- How do I set a auto increment key in Realm?
- Realm and auto increment Behavior (Android)
- https://github.com/realm/realm-java/issues/469
It says, that the Primary Key Auto Increment is not supported on Realm. OK, so I want to add that myself. The linked posts shows ways to do that.
Problem: The proposed solutions require to manually add a getNextPrimaryId()
function for every model class myself. That seems extremely stupid to do. I tried to write a generic one myself in Swift so I only have to do that once and it will apply to all my model classes automatically, but I failed.
Attempt 1:
extension Object {
func autoIncId() -> Int {
let objects = Database.realm.objects(self).sorted("id")
// Filter the max id here and return + 1
}
}
Attempt 2:
class Database {
static func autoIncId(type: Object) -> Int {
let currentId = Database.realm.objects(type.self).map{$0.id}.maxElement ?? 0
return currentId + 1
}
}
Both don't compile because "Cannot convert value of type "Object" to expected argument type "Object.Type"
".
Does anyone have any idea how to write generic function that applies to ALL models automatically? I simply would like to just call MyModelClass.autoIncId()
to get the next id.