Seeing strange generic behavior, which leads me to believe I'm missing something in my understanding.
I am using the following method to loop throw a JSON response and call a generic method. User
, Card
and Ecard
all inherit from IDObject
, which in turn inherits from Object
(a Realm class)
let props:[(label:String, type:IDObject.Type)] = [
(label: "deletedUsers", type: User.self),
(label: "deletedCards", type: Card.self),
(label: "deletedECards", type: Ecard.self)
]
for prop in props {
if let ids = json[prop.label].arrayObject as? [Int], ids.count > 0 {
DataManager.shared.delete(prop.type, ids: ids)
}
}
func delete<T:IDObject>(_ type:T.Type, ids:[Int]) {
guard ids.count > 0 else { return }
if let objectsToDelete = objects(type, where: NSPredicate(format: "identifier IN %@", ids)) {
delete(objectsToDelete)
}
}
func delete<T:Object>(_ objects:Results<T>) {
guard objects.count > 0 else { return }
do {
let realm = try Realm()
try realm.write {
realm.delete(objects)
}
} catch {
print(error)
}
}
The delete(_ type:T.Type, ids:[Int])
function can not infer the generic type this way.
However, unwrapping the for prop in props
loop works as expected.
if let userIds = json["deletedUsers"].arrayObject as? [Int], userIds.count > 0 {
DataManager.shared.delete(User.self, ids: userIds)
}
Do generics only work at compile time, or is there a way to handle this dynamically at runtime?