Reputation: 953
I have custom function which is store data to Core data. But I don't want to duplicate the function many times depends on how many attributes i have. I want to create one function that i can use it with any attribute i want.
if #available(iOS 10.0, *) {
fetchRequest = MyUser.fetchRequest()//How to make this Changeable?
} else {
fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: changeableEntity)
}
Is there anyway that i can make the attribute "MyUser".fetchRequest() .. Changeable to any other attribute without duplicate the function many times?
class func MyCustomFunc(attribute: ??, changeableEntity:String)
Any help will be appreciated.
Upvotes: 0
Views: 55
Reputation: 7385
You could use a function which passes the Object Type as a generic as per the following example:
/// Generates A Standard Fetch Request On A Generic NSManagedObject Type
///
/// - Parameter key: String
/// - Returns: NSFetchRequest<NSFetchRequestResult>
func generatedFetchRequestFor<Object: NSManagedObject>(_ key: String, entityClass: Object.Type ) -> NSFetchRequest<NSFetchRequestResult>{
var request: NSFetchRequest<NSFetchRequestResult>!
if #available(iOS 10.0, *) {
request = entityClass.fetchRequest()
} else {
let entityName = String(describing: entityClass)
request = NSFetchRequest(entityName: entityName)
}
let sortDescriptor = NSSortDescriptor(key: key, ascending: true)
request.sortDescriptors = [sortDescriptor]
return request
}
An example use would thus be:
let request = generatedFetchRequestFor("id", entityClass: MyUser.self)
Upvotes: 1