iOS - Swift:如何为这种情况编写泛型函数?

时间:2016-12-15 08:35:19

标签: ios swift xcode swift3 generic-programming

我在我的应用中使用了CoreData。数据库中有4个表:用户,医学,时间表和患者。对于每个表,我需要编写一个Add函数来将数据添加到数据库中,如下所示:

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与它进行比较。或者有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

针对此案例的最快解决方案,因为每个Entity具有不同的save实现,就是声明Saveable协议

protocol Saveable {
    associatedtype Parameters
    static var entityName: String { get }
    static var context: NSManagedContext { get }
    func setup(with parameters: Parameters)
    func save(_ handler: () -> ())
}

然后将此协议用作addDataToDB函数

中的通用参数
func addDataToDB<T>(params: T.Parameters, _ handler: () -> ()) where T: Saveable {
    let entity = NSEntityDescription.entity(forEntityName: T.entityName, in: T.contenxt)!
    let object = NSManagedObject(entity: entity, insertInto: T.context) as! T
    object.setup(with: params)

    object.save(handler)
}
在这种情况下,

Parameters应该是struct,或字典,完全取决于你