2
我在我的应用程序中使用CoreData。数据库中有4个表格:用户,医学,时间表和患者。对于每一个表,我需要写一个Add函数将数据添加到数据库这样的:iOS - Swift:如何为这种情况编写泛型函数?
func addUser(email: String, password: NSData, handler: @escaping (_ status: SaveStatus, _ error: NSError?) -> Void){
let managedContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: DB.TABLE.USER, in: managedContext!)!
let nurse = NSManagedObject(entity: entity, insertInto: managedContext) as! User
nurse.email = email
nurse.password = password
save { (status, error) in
handler(status, error)
}
}
func addMedicine(name: String, handler: @escaping(_ status: SaveStatus, _ error: NSError?) -> Void){
let managedContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: DB.TABLE.MEDICINE, in: managedContext!)!
let medicine = NSManagedObject(entity: entity, insertInto: managedContext) as! Medicine
medicine.name = name
save { (status, error) in
handler(status, error)
}
}
等等...
我想写这样一个泛型函数:
func addDataToDB<DATA>(object: DATA, handler: @escaping SaveStatusHandler){
switch DATA {
case DATA is LoginData:
break
default:
break
}
}
我不知道LoginData应该是什么类型,所以我可以将它与DATA进行比较。或者有没有更好的方法来做到这一点?
如果我想按照自己的方式来做,它有什么解决方案? –
@HoangTrung如果你想用你的方式来做,你根本不会使用泛型。只需使用'Any'参数并切换其类型... –
哦,我现在看到了,谢谢。还有一个问题,如果我定义一个结构例如LoginData,如何检查参数是否是LoginData类型? –