Select function in swift 3. Any suggestion?

Hi everyone,

I’m studying swift to update my apps and I’ve some problem.

in objective-C to fetch from core data some data I’ve written an method that inserting some condition, fetch data from some entity.

this is Objective-c code

- (NSMutableArray *)selectFromTable:(NSString *)tableName Where:(NSString *)condition OrderBy:(NSString *)sorting isAscending:(BOOL)ascending{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext];
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:tableName];
    if (condition != nil) {
        fetchRequest.predicate = [NSPredicate predicateWithFormat:condizione];
    if (sorting != nil) {
        NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:sorting ascending:ascending];
        fetchRequest.sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, nil];
    NSError *error;
    NSArray *objects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    return [objects mutableCopy];

There is a way to do this in swift 3?

I’ve written this function, but give me an error

func select(fromTable:String, Where:String, OrderBy:String, isAscending:Bool) -> NSMutableArray {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Kanji")
        fetchRequest.returnsObjectsAsFaults = false
        if !Where.isEmpty {
            fetchRequest.predicate = NSPredicate(format: Where, CVarArg.self as! CVarArg)
        if !OrderBy.isEmpty {
            fetchRequest.predicate = NSPredicate(format: OrderBy, CVarArg.self as! CVarArg)
        let results:NSMutableArray = try managedObjectContext.fetch(fetchRequest) //<- give me this error:Cannot invoke 'fetch' with an argument list of type '(NSFetchRequest<NSFetchRequestResult>)'
        return results

How can I fix it?


I’m sorry. I’ve forget one thing:
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

this is code I use to get managedObjectContext