import Foundation
import CoreData

class CoreDataStack {
    var container: NSPersistentContainer {
        let container = NSPersistentContainer(name: "todos")
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.loadPersistentStores { (description, error) in
            guard error == nil else {
                print("Error: \(error!)")
                return
            }
        }
        return container
    }

    var managedContext: NSManagedObjectContext {
        return container.viewContext
    }
}

In an alert view:

 let action = UIAlertAction(title: "Update", style: .default) { (_) in

        let name = alert.textFields!.first!.text!
        let age = alert.textFields!.last!.text!


        selectedItem.setValue(name, forKey: "name")
        selectedItem.setValue(Int16(age), forKey: "age")

        do{
            try persistenceService.context.save()
        } catch {
            print("Error saving")
        }

        self.tableView.reloadData()
    }

In a tableview:

        let itemToDelete = people[indexPath.row]

    print(itemToDelete)

    if (editingStyle == UITableViewCellEditingStyle.delete) {
        // handle delete (by removing the data from your array and updating the tableview)

        persistenceService.context.delete(itemToDelete)
        self.people.remove(at: indexPath.row)

        do {
            try persistenceService.context.save()
        } catch let error as NSError {
            print("Error While Deleting: \(error.userInfo)")
        }


    }

In an alert view:

 let action = UIAlertAction(title: "Save", style: .default) { (_) in
            let name = alert.textFields!.first!.text!
            let age = alert.textFields!.last!.text!

//            fill container
            let person = Person(context: persistenceService.context)
            person.name = name
            person.age = Int16(age)!

//            save container
            persistenceService.saveContext()
            self.people.append(person)

        self.tableView.reloadData()

    }